RapidJson解析json的数组

时间:2015-01-06 13:58:28

标签: rapidjson

如果我有这种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());

如果它甚至没有密钥,如何提取数组?

1 个答案:

答案 0 :(得分:1)

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

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

  2. 在数组前添加密钥,例如{ "a" : [ ... ] }。然后,您可以通过doc["a"]

  3. 访问数组