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

How to find the number of objects or array in a JSON data using jsonCpp

本文关键字:对象 数组 jsonCpp 何使用 查找 JSON 数据      更新时间:2023-10-16

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

给定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数据中的键值元素的数量?

您可以使用Json::Value对象的size成员函数,如下所示。你的数据不可行,所以我从别的地方弄了一些,但我想你会看到共同点的。

您发布的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 parsen";
        return;
    }
    cout << "parsed okn";
    // 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() << " elementsn";
    }
}
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 parsen";
        return;
    }
    cout << "parsed okn";
    // 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() << " elementsn";
    }
}
int main()
{
    named();
    unnamed();
}