c++ - 使用 json 库创建 json 字符串

标签 c++ c json string

我正在使用 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
}

如何添加与作者详细信息关联的顶部?

最佳答案

套用一句旧广告的话,“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"];

或者,假设我们找到了一个帖子,所以我们想要增加帖子的数量。这是事情变得……不那么有品位的地方——我们不能随心所欲地直接增加值(value);我们必须获取值,加一,然后分配结果(就像我们在缺少 ++ 的较小语言中所做的那样):

j["author-details"]["Number of Posts"] = j["author-details"]["Number of Posts"] + 1;

然后我们要写出结果。如果我们想要它“密集”(例如,我们要通过网络传输它以供其他机器读取)我们可以只使用 << :

somestream << j;

另一方面,我们可能希望对其进行 pretty-print ,以便人们可以更轻松地阅读它。该库尊重我们使用 setw 设置的宽度, 所以要打印出带有 4 列制表位的缩进,我们可以这样做:

somestream << std::setw(4) << j;

关于c++ - 使用 json 库创建 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42956555/

相关文章:

c++ - CMake 使库需要 cxx 标准

c++ - 操作系统全局描述符表编译错误

c++ - YAML 未解析的外部符号 (yaml-cpp)

c++ - 将具有默认值的数组作为参数传递给 int main()

c - 将数组中的值设置为仅等于 1 或 0

c - 使用函数范围到期释放结构链表的内存

javascript - 在 jQuery.parseJSON 中引用

json - GraphQL 和 rest api 有什么区别

c - 如何将数组中的第一个元素分配给变量?

python - 在 Python 中从 curl 读取 JSON 文件