Home > Software design >  user writes access path to a nested element in a JSON file
user writes access path to a nested element in a JSON file

Time:01-14

I wrote a code that prompts the user for the access path to an element in a JSON file and then retrieves the value of that element. But I can only get access to a root element. What should user write to e.g. get object.array[2].field? I use single include nlohmann/json library.

My code:

using json = nlohmann::json;

int main() {
std::ifstream file("test3.json");
json data;
file >> data;

std::string access_path;
std::cout << "Enter the access path to the nested element (e.g. 'object.array[2].field'): ";
std::getline(std::cin, access_path);

try {
    json nested_element = data.at(access_path);
    std::cout << "Value of element: " << nested_element.dump() << std::endl;
} catch (json::out_of_range& e) {
    std::cout << "Error: Invalid access path." << std::endl;
}

return 0;
}

CodePudding user response:

First of all, you need a json_pointer.

json nested_element = data.at(json::json_pointer(access_path));

Then accessing field in array[2] in object would be entered by the user as

/object/array/2/field

Example version of the test3.json file:

{
        "object": {
                "array": [{
                                "field": "foo"
                        },

                        {
                                "field": "bar"
                        },
                        {
                                "field": "hello world"
                        }
                ]
        }
}

Output:

Value of element: "hello world"
  • Related