如何使用jsonCpp查找JSON数据中的对象或数组的数量

时间:2016-08-10 02:49:05

标签: c++ json jsoncpp

我的主要需求是如何找到顶级数据中的元素数量。

鉴于json数据:

{
 [
  {Key11:Value11,Key12:Value12,...Key1N:Value1N},
  {Key21:Value21,Key22:Value22,...Key2N:Value2n},
  {Key31:Value31,Key32:Value32,...Key3N:Value3N},
  {Key41:Value41,Key42:Value42,...Key4N:Value4N},
  .
  .
  .
  KeyZ1:ValueZ1,KeyZ2:ValueZ2,...KeyZN:ValueZN}
 ]
}

如何在Json数据中找到数组元素的数量?

另外,鉴于jason数据:

{
 {Key11:Value11,Key12:Value12,...Key1N:Value1N}
}

如何在json数据中找到键值元素的数量?

1 个答案:

答案 0 :(得分:3)

您可以使用size对象的Json::Value成员函数,就像这样。你的数据不可行,所以我从其他地方得到了一些,但我认为你会看到共性。

您发布的json数据在语法上不正确。要使其有效,您必须为列表元素命名或删除外部{}。我已经为两种可能性提供了解决方案

#include <cstdio>
#include <cstring>
#include <iostream>

#include "json/json.h"

using namespace std;

void named()
{
    string txt = "{                 \
    \"employees\": [{               \
        \"firstName\": \"John\",    \
        \"lastName\": \"Doe\"       \
    }, {                            \
        \"firstName\": \"Anna\",    \
        \"lastName\": \"Smith\"     \
    }, {                            \
        \"firstName\": \"Peter\",   \
        \"lastName\": \"Jones\"     \
    }]                              \
    }";


    Json::Value root;
    Json::Reader reader;

    bool ok = reader.parse(txt, root, false);

    if(! ok) 
    {
        cout << "failed parse\n";
        return;
    }

    cout << "parsed ok\n";

    // Answer to question 1
    cout << "The employee list is size " << root["employees"].size() << '\n';

    for(const auto& jv: root["employees"])
    {
        // Answer to your second question
        cout << "employee " << jv["firstName"] << " has " << jv.size() << " elements\n";
    }
}

void unnamed()
{
    string txt2 = "[{               \
        \"firstName\": \"John\",    \
        \"lastName\": \"Doe\"       \
    }, {                            \
        \"firstName\": \"Anna\",    \
        \"lastName\": \"Smith\"     \
    }, {                            \
        \"firstName\": \"Peter\",   \
        \"lastName\": \"Jones\"     \
    }]";

    Json::Value root;
    Json::Reader reader;

    bool ok = reader.parse(txt2, root, false);

    if(! ok) 
    {
        cout << "failed parse\n";
        return;
    }

    cout << "parsed ok\n";

    // Answer to question 1
    cout << "The employee list is size " << root.size() << '\n';

    for(const auto& jv: root)
    {
        // Answer to your second question
        cout << "employee " << jv["firstName"] << " has " << jv.size() << " elements\n";
    }
}

int main()
{
    named();
    unnamed();
}