Skip to content

Read nested values from an array


Example on how to read nested values from an array.
Because json arrays rarely contain just atomics :D

Let's also make the array a labelled field itself.

We have this json:
{
    "comments": [
        {
            "author": "Topper McNabb",
            "message": "Shine yer armor for a copper.",
            "timestamp": 1178064000
        },
        {
            "author": "Ner'zhul",
            "message": "I...have dreamed of you. I have had visions of death, and now you are here.",
            "timestamp": 1240617600
        },
        {
            "author": "Arthas Menethil",
            "message": "This entire city must be purged.",
            "timestamp": 1021939200
        },
        {
            "author": "Terenas Menethil II",
            "message": "At long last. No king rules forever, my son.",
            "timestamp": 1258156800
        }
    ]
}
C++:
Json json;
json.Parse(aboveJsonCode);

JsonArray& comments = json.AsJson.Get("comments").AsArray;

for (unsigned int i = 0; i < comments.Size(); i++)
{
    std::string author  = comments[i].AsJson.Get("author").AsString;
    std::string message = comments[i].AsJson.Get("message").AsString;
    time_t timestamp    = comments[i].AsJson.Get("timestamp").AsInt;

    std::cout << author << ": " << std::endl
              << message << std::endl << std::endl;
}