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
        }
    ]
}
Quick and dirty (C++):
Json json;
json.Parse(aboveJsonCode);

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

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

This does look nice, but it does not perform well. You should cache that array!

Properly (Caching the array) (C++):
Json json;
json.Parse(aboveJsonCode);

JsonArray& comments = json["comments"].AsArray;

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

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