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,看起来像这样:

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

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字典等效的内容.

推荐答案

  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).

  2. 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.

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

Json相关问答推荐

在Go中,当字段可以根据其他字段具有不同的类型时,什么是正确的方法来卸载JSON?

从JSON格式提取数据时分隔通用名称

从Razor Pages的AJAX Json呈现DataTables问题.Net GET

如何在Gatsby/Reaction中获取JSON-File子 node

时间序列的Vega Lite分组条形图

如何让JSON子查询在没有行的情况下返回空数组而不是NULL

将pyspark.sql.Rowtype数据转换为Json字符串,消除Azure Databricks NB中的值

爆炸没有数组的 struct pyspark

打印与 JSON 和 PowerShell 中的模式匹配的子项的父项名称

如何在 Android Studio 中将 List 字段作为空列表[]返回?

如何在 Go 中生成带有排序键的 JSON?

应该使用什么标头将 GZIP 压缩 JSON 从 Android 客户端发送到服务器?

Java JSON 序列化 - 最佳实践

十六进制格式可以与 JSON 文件一起使用吗?如果是这样,怎么做?

Android JSON 库的性能和可用性比较

ASP.NET MVC:使用 JsonResult 控制属性名称的序列化

如何使用 Jackson 注释从 HttpResponse 反序列化 JSON 对象?

通过 JSON 发送 HTML 代码

JSON JQ 如果没有 else

严重:找不到媒体类型 = 应用程序/json、类型 = 类 com.jersey.jaxb.Todo、通用类型 = 类 com.jersey.jaxb.Todo 的 MessageBodyWriter