gpt4 book ai didi

c++ - 在 C++ 中读取 json 文件

转载 作者:IT老高 更新时间:2023-10-28 22:19:52 27 4
gpt4 key购买 nike

我正在尝试读取 JSON 文件。到目前为止,我一直专注于使用 jsoncpp 库。但是,文档对我来说很难理解。任何人都可以用通俗的术语解释它的作用吗?

假设我有一个 people.json,它看起来像这样:

{"Anna" : { 
"age": 18,
"profession": "student"},
"Ben" : {
"age" : "nineteen",
"profession": "mechanic"}
}

当我读到这篇文章时会发生什么?我可以创建某种数据结构 people 我可以通过 AnnaBen 以及 age职业people 的数据类型是什么?我认为它类似于(嵌套) map ,但 map 值总是必须具有相同的类型,不是吗?

我以前使用过 python,我的“目标”(对于 C++ 来说可能是错误的)是获得一个嵌套的 python 字典的等价物。

最佳答案

  1. 是的,你可以创建一个嵌套的数据结构 people,它可以被 AnnaBen 索引。但是,不能直接按ageprofession来索引(这部分我会在代码中讲到)。

  2. people的数据类型是Json::Value类型(在jsoncpp中定义)。没错,它类似于嵌套映射,但是 Value 是一种数据结构,它被定义为可以存储和访问多种类型。它类似于以 string 作为键和 Json::Value 作为值的映射。它也可以是 unsigned int 作为键和 Json::Value 作为值之间的映射(如果是 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对象进行索引。

关于c++ - 在 C++ 中读取 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32205981/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com