使用 json lib 创建 json 字符串
Posted
技术标签:
【中文标题】使用 json lib 创建 json 字符串【英文标题】:Creating json string using json lib 【发布时间】:2017-03-22 15:47:00 【问题描述】:我正在使用jsonc-libjson 创建如下所示的 json 字符串。
"author-details":
"name" : "Joys of Programming",
"Number of Posts" : 10
我的代码如下所示
json_object *jobj = json_object_new_object();
json_object *jStr1 = json_object_new_string("Joys of Programming");
json_object *jstr2 = json_object_new_int("10");
json_object_object_add(jobj,"name", jStr1 );
json_object_object_add(jobj,"Number of Posts", jstr2 );
这给了我json字符串
"name" : "Joys of Programming",
"Number of Posts" : 10
如何添加与作者详细信息相关的顶部?
【问题讨论】:
【参考方案1】:套用一句老广告的话,“libjson 用户宁愿战斗也不愿切换。”
至少我认为你一定喜欢和图书馆打架。使用nlohmann's JSON library,您可以使用如下代码:
nlohmann::json j
"author-details",
"name", "Joys of Programming" ,
"Number of Posts", 10
;
至少对我来说,这似乎更简单,更易读。
解析同样简单。例如,假设我们有一个名为 somefile.json
的文件,其中包含上面显示的 JSON 数据。要读取和解析它,我们可以这样做:
nlohmann::json j;
std::ifstream in("somefile.json");
in >> j; // Read the file and parse it into a json object
// Let's start by retrieving and printing the name.
std::cout << j["author-details"]["name"];
或者,假设我们找到了一个帖子,所以我们想要增加帖子的数量。这是一个让事情变得……不那么有品味的地方——我们不能随心所欲地直接增加价值;我们必须获取值,加一,然后分配结果(就像我们在缺少++
的较少语言中所做的那样):
j["author-details"]["Number of Posts"] = j["author-details"]["Number of Posts"] + 1;
然后我们要写出结果。如果我们希望它“密集”(例如,我们将通过网络传输它以供其他机器读取),我们可以使用<<
:
somestream << j;
另一方面,我们可能想要漂亮地打印它,以便人们可以更轻松地阅读它。库尊重我们使用setw
设置的宽度,因此要打印出带有 4 列制表位的缩进,我们可以这样做:
somestream << std::setw(4) << j;
【讨论】:
我支持使用 nlohmann 库的动议。我以前用过,没有太多麻烦,而且很成功。 感谢大家推荐 nlohmann 的 JSON。我会试试的。首先,如果有人可以使用 nlohman 的 json 库抛出如何解析 json 数据/对象的 sn-p,那就太好了。【参考方案2】:创建一个新的 JSON 对象并添加您作为子对象已经创建的对象。
在你已经写好的之后插入这样的代码:
json_object* root = json_object_new_object();
json_object_object_add(root, "author-details", jobj); // This is the same "jobj" as original code snippet.
【讨论】:
它不会产生预期的结果。 json_object jobj = json_object_new_object(); json_object root = json_object_new_object (); json_object_object_add(jobj,“作者详细信息”,根);我在之前提供的代码之前添加了这个。 json_object *jobj = json_object_new_object(); json_object *jStr1 = json_object_new_string("编程的乐趣"); json_object *jstr2 = json_object_new_int(10);它打印 "author-details": , "name": "Joys of Programming", "Number of Posts": 10 【参考方案3】:根据多米尼克的评论,我能够找出正确的答案。
json_object *jobj = json_object_new_object();
json_object* root = json_object_new_object();
json_object_object_add(jobj, "author-details", root);
json_object *jStr1 = json_object_new_string("Joys of Programming");
json_object *jstr2 = json_object_new_int(10);
json_object_object_add(root,"name", jStr1 );
json_object_object_add(root,"Number of Posts", jstr2 );
【讨论】:
以上是关于使用 json lib 创建 json 字符串的主要内容,如果未能解决你的问题,请参考以下文章