在C ++中读取json文件

用户名

我正在尝试读取JSON文件。到目前为止,我一直专注于使用该jsoncpp库。但是,文档对我来说很难理解。谁能用俗语解释它的作用?

说我有一个people.json看起来像这样的:

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

当我读到这篇文章时会发生什么?我可以建立某种形式的数据结构people,我可以指数AnnaBen以及ageprofession的数据类型是people什么?我以为这类似于(嵌套的)地图,但是地图值始终必须具有相同的类型,不是吗?

我之前使用过python,而我的“目标”(对于C ++来说可能是个问题)是获得与嵌套python字典等效的结果。

Pooja Nilangekar
  1. 是的,您可以创建一个people可由Anna索引的嵌套数据结构Ben但是,您不能通过age直接对其进行索引profession(我将在代码的这一部分进行介绍)。

  2. 的数据类型为people类型Json::Value(在jsoncpp中定义)。没错,它类似于嵌套映射,但是它Value是一种数据结构,定义该数据结构可以存储和访问多种类型。它类似于以astring作为键和Json::Value的映射它也可以是unsigned intas键和Json::Valueas值之间的映射(对于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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章