我正在尝试读取JSON文件。到目前为止,我一直专注于使用该jsoncpp
库。但是,文档对我来说很难理解。谁能用俗语解释它的作用?
说我有一个people.json
看起来像这样的:
{"Anna" : {
"age": 18,
"profession": "student"},
"Ben" : {
"age" : "nineteen",
"profession": "mechanic"}
}
当我读到这篇文章时会发生什么?我可以建立某种形式的数据结构people
,我可以指数Anna
和Ben
以及age
和profession
?的数据类型是people
什么?我以为这类似于(嵌套的)地图,但是地图值始终必须具有相同的类型,不是吗?
我之前使用过python,而我的“目标”(对于C ++来说可能是个问题)是获得与嵌套python字典等效的结果。
是的,您可以创建一个people
可由Anna
和索引的嵌套数据结构Ben
。但是,您不能通过age
和直接对其进行索引profession
(我将在代码的这一部分进行介绍)。
的数据类型为people
类型Json::Value
(在jsoncpp中定义)。没错,它类似于嵌套映射,但是它Value
是一种数据结构,定义该数据结构可以存储和访问多种类型。它类似于以astring
作为键和Json::Value
值的映射。它也可以是unsigned int
as键和Json::Value
as值之间的映射(对于json数组)。
这是代码:
#include <json/value.h>
#include <fstream>
std::ifstream people_file("people.json", std::ifstream::binary);
people_file >> people;
cout<<people; //This will print the entire json object.
//The following lines will let you access the indexed objects.
cout<<people["Anna"]; //Prints the value for "Anna"
cout<<people["ben"]; //Prints the value for "Ben"
cout<<people["Anna"]["profession"]; //Prints the value corresponding to "profession" in the json for "Anna"
cout<<people["profession"]; //NULL! There is no element with key "profession". Hence a new empty element will be created.
如您所见,您只能基于输入数据的层次结构为json对象建立索引。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句