Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Checking keys of two jsons against eachother #1465

Closed
simulationcloud opened this issue Jan 30, 2019 · 5 comments
Closed

Checking keys of two jsons against eachother #1465

simulationcloud opened this issue Jan 30, 2019 · 5 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@simulationcloud
Copy link

So, I have two JSON configuration files that may be nested multiple layers deep. One consists of all possible parameters a user can input set to their default value. The other is JSON input from a user. I want to check that no key (including nested keys) exists in the user JSON that does not exist in the configuration JSON.

Is there a simple way to do this?

Thank you very much in advance!

@nlohmann
Copy link
Owner

You could try the diff function.

@nickaein
Copy link
Contributor

I am not sure whether there is an easier way of checking that, but here is a solution:

bool verify_with_schema(const json& schema, const json& user)
{
    for(auto& item_user: user.items()) 
    {
        auto item_schema = schema.find(item_user.key());
        if(item_schema == schema.cend())
            return false;

        if(item_user.value().is_object())
        {
            if(!verify_with_schema(*item_schema, item_user.value()))
            return false;
        }
    }

    return true;
}

I haven't tested it thoroughly though. Please check it before using it in production.

@nickaein
Copy link
Contributor

@simulationcloud Forget the above function. Based on nlohmann comment, there is already infrastructure for comparing two JSONs. It also let you find out which values has been actually overridden by the user (indicated by replace operation).

@nlohmann
Copy link
Owner

@simulationcloud Do you need further assistance?

@simulationcloud
Copy link
Author

simulationcloud commented Feb 12, 2019 via email

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Feb 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

3 participants