Search code examples
rapidjson

RapidJson parsing array of json


What to do if I have this kind of json? I'm using rapidjson

{[
    {
        "username": "A",
        "level": "1",
        "score": "1774"
    },
    {
        "username": "Ab",
        "level": "1",
        "score": "1923"
    },
    {
        "username": "M",
        "level": "1",
        "score": "1991"
    },
    {
        "username": "P",
        "level": "1",
        "score": "2030"
    },
    {
        "username": "Am",
        "level": "1",
        "score": "2044"
    }
]}

This will surely failed the assert.

rapidjson::Document doc;
doc.Parse<0>(message.c_str());
assert(doc.IsObject());

and how to extract the array if it doesn't even have a key?


Solution

  • This is not a valid JSON. For JSON object, i.e. { ... }, it should contains key-value pairs. Two solutions:

    1. You can simply remove the out-most { } to make it a valid JSON. Then the root will be an JSON array, and doc.IsArray() == true.

    2. Add a key before the array, e.g. { "a" : [ ... ] }. Then you can access the array by doc["a"].