Json: [Feature request] Access by path

Created on 13 Apr 2018  路  7Comments  路  Source: nlohmann/json

It would be great if there was accessors by path in a JSON object:

for example, if we have a JSON object x containing

{
    "foo": {
        "bar": {
            "value": 1   
        },
        "baz": {
            "value": 3
        }
    }
}

x[{"foo", "baz"}] would return a JSON object containing

{
    "value": 3
}
proposed fix

Most helpful comment

@theodelrieu is right. JSON Pointers can do this:

#include <iostream>
#include "json.hpp"

using json = nlohmann::json;

int main()
{
    json j = R"({
        "foo": {
            "bar": {
                "value": 1
            },
            "baz": {
                "value": 3
            }
        }
    })"_json;

    std::cout << j["/foo/baz"_json_pointer] << std::endl;
}

All 7 comments

cc @martinRenou

What is the difference to x["foo"]["baz"]?

What is the difference to x["foo"]["baz"]?

The difference is the unknown number of elements in the sequence.

I guess that we could have an API based on iterator pairs for the sequence, and have the initializer list and container-based version rebind to it.

What about an accessor with an iterator pair

JSON.at(first, last)

although the value type for the iterator should be a string / integral, or a variant containing string or some integral type. I guess it is not that simple.

Isn't json_pointer what you're looking for?

@theodelrieu is right. JSON Pointers can do this:

#include <iostream>
#include "json.hpp"

using json = nlohmann::json;

int main()
{
    json j = R"({
        "foo": {
            "bar": {
                "value": 1
            },
            "baz": {
                "value": 3
            }
        }
    })"_json;

    std::cout << j["/foo/baz"_json_pointer] << std::endl;
}

Thanks! I did not know about this!

Was this page helpful?
0 / 5 - 0 ratings