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

use*_*124 3 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}
 ]
}
Run Code Online (Sandbox Code Playgroud)

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

此外,鉴于杰森数据:

{
 {Key11:Value11,Key12:Value12,...Key1N:Value1N}
}
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*ney 5

您可以像这样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();
}
Run Code Online (Sandbox Code Playgroud)