user8639911
user8639911

Reputation:

C++ nonlohmann json read child object

i'm actually working on a little program and i need to read a json file. i'm using C++ and the nlohmann json libraries.

My current code

int main(int argc, const char** argv){
    ifstream ifs("Myjson.json");
    json j = json::parse(ifs);
    cout << "Front image path : "<< j["front"]["imagePath"]  << "\n";
    cout << "Back image path : " << j["back"]["imagePath"] << "\n";

    system("PAUSE");
    return 0;
}

MyJson.json

{
    "Side": [
        {
            "camera": "22344506",
            "width": 19860,
            "nbParts": 662,
            "wParts": 30,
            "height": 1600,
            "imagePath": "./Tchek_buffer/22344506.png"
        },
        {
            "camera": "22344509",
            "width": 5296,
            "nbParts": 662,
            "wParts": 8,
            "height": 1600,
            "imagePath": "./Tchek_buffer/22344509.png"
        },
    ],
    "front": {
        "camera": "22344513",
        "image": null,
        "width": 1200,
        "height": 1600,
        "imagePath": "./Tchek_buffer/22344513.png"
    },
    "back": {
        "camera": "22344507",
        "image": null,
        "width": 1600,
        "height": 1200,
        "imagePath": "./Tchek_buffer/22344507.png"
    },
}

I can easily read and display the "back" and the "front" object but i can't read the scanner object. i want to get the "imagePath" of all "scanner" object

i tried thing like

cout << "scanner image path : " << j["scanner"]["imagePath"] << "\n";
cout << "scanner image path : " << j["scanner[1]"]["imagePath"] << "\n";
cout << "scanner image path : " << j["scanner"[1]]["imagePath"] << "\n";

i only get "null" result

if someone can help me and explain me how i can make it work .

Upvotes: 0

Views: 1630

Answers (2)

Caduchon
Caduchon

Reputation: 5231

I suppose "Side" and "scanner" is equivalent in your question. You probably did a mismatch between the tags.

I don't know this library, but I suppose it's something like that:

cout << "scanner image path 1 : " << j["scanner"][0]["imagePath"] << "\n";
cout << "scanner image path 2 : " << j["scanner"][1]["imagePath"] << "\n";

You can find an example from documentation here.

Upvotes: 0

Jean-Bernard Jansen
Jean-Bernard Jansen

Reputation: 7870

Assuming scanner is in fact Side in the json.

Your trials did the following:

  • Access the "imagePath" property of the list
  • Access the "scanner[1]" property of the list
  • Access the "c" (second character) property of the list.

So the dirty way to go would be :

cout << "scanner image path : " << j["Side"][0]["imagePath"] << "\n";
cout << "scanner image path : " << j["Side"][1]["imagePath"] << "\n";

And the proper one would be:

for (auto& element : j["Side"])
  cout << "scanner image path : " << element["imagePath"] << "\n";

Upvotes: 2

Related Questions