RapidJson 解析数组 json

RapidJson parsing array of json

我有这种json怎么办?我正在使用 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"
    }
]}

这肯定会使断言失败。

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

如果数组连键都没有,如何提取数组?

这不是有效的 JSON。对于 JSON 对象,即 { ... },它应该包含键值对。两种解决方案:

  1. 您只需删除最外面的 { } 即可使其成为有效的 JSON。然后根将是一个 JSON 数组,并且 doc.IsArray() == true.

  2. 在数组前添加一个键,例如{ "a" : [ ... ] }。然后你可以通过 doc["a"].

  3. 访问数组