在C ++中读取json文件 [英] Reading json files in C++

查看:102
本文介绍了在C ++中读取json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to read in a JSON file. So far I have focused on using the jsoncpp library. However, the documentation is quite hard to understand for me. Could anyone explain in lay terms what it does?

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

Say I have a people.json which looks like this:

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

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

What happens when I read this in? Can I create some sort of data structure people which I can index by Anna and Ben as well as age and profession? What would be the data type of people? I thought it would be something similar to a (nested) map, but map values always have to have the same type, don't they?

我以前使用过python,而我的目标"(对于C ++来说可能是个弊端)是要获得与嵌套python字典等效的结果.

I have worked with python before and my "goal" (which may be ill-set for C++) is to obtain the equivalent of a nested python dictionary.

推荐答案

  1. 是的,您可以创建一个嵌套的数据结构people,该结构可以由AnnaBen进行索引.但是,您不能直接通过ageprofession对其进行索引(我将在代码中找到这部分).

  1. Yes you can create a nested data structure people which can be indexed by Anna and Ben. However, you can't index it directly by age and profession (I will get to this part in the code).

people的数据类型为Json::Value类型(在jsoncpp中定义).没错,它类似于嵌套映射,但是Value是一种数据结构,定义该数据结构可以存储和访问多种类型.它类似于以string作为键和Json::Value作为值的映射.它也可以是unsigned int作为键和Json::Value作为值之间的映射(对于json数组).

The data type of people is of type Json::Value (which is defined in jsoncpp). You are right, it is similar to the nested map, but Value is a data structure which is defined such that multiple types can be stored and accessed. It is similar to a map with a string as the key and Json::Value as the value. It could also be a map between an unsigned int as key and Json::Value as the value (In case of json arrays).

代码如下:

#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对象建立索引.

As you can see, you can index the json object only based on the hierarchy of the input data.

这篇关于在C ++中读取json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆