如何使用jsonCpp查找JSON数据中的对象或数组的数量
How to find the number of objects or array in a JSON data using 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数据中的键值元素的数量?
您可以使用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();
}
相关文章:
- 将对象数组的引用传递给函数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 类对象数组的问题会导致崩溃
- Arduino C++在构造函数中用参数声明对象数组
- 使用对象数组对 SFML 进行动画处理
- C++ 对象数组堆栈溢出
- 如何将对象数组作为参数传递给模板
- 使用向量初始化参数化构造函数的对象数组
- 如何初始化对象数组?
- C++创建对象数组
- 在对象数组中搜索字符串并返回相应值的函数
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 为什么我在声明对象数组时不能使用 -> 运算符?
- 编译时生成应在构造函数中创建的非 constexpr 对象数组
- 使用 C++ 创建对象数组
- 对象数组打印空白字符串
- 重载运算符 [] 用于从对象数组中给出特定索引
- 如何在 C++ 中使用提升属性树从 JSON 文件中读取对象数组