我正在使用https://github.com/nlohmann/json并且效果很好。但是我发现很难创建以下 json outout
{
"Id": 1,
"Child": [
{
"Id": 2
},
{
"Id": 3,
"Child": [
{
"Id" : 5
},
{
"Id" : 6
}
]
},
{
"Id": 4
}
]
}
每个节点都必须有一个 id 和一个数组(“Child”元素)。任何孩子都可以递归地继续拥有 Id 或 Child。上面的json只是一个例子。我想要的是使用 nlohmann json 在父节点和子节点之间创建一个链。
数字 1, 2, 3, .... 是随机选取的。我们现在不关心这些值。
知道如何创建它吗?
到目前为止的代码
#include <iostream>
#include <string>
#include <vector>
#include "json.hpp"
using json = nlohmann::json;
struct json_node_t {
int id;
std::vector<json_node_t> child;
};
int main( int argc, char** argv) {
json j;
for( int i = 0; i < 3; i++) {
json_node_t n;
n.id = i;
j["id"] = i;
if ( i < 2 ) {
j["child"].push_back(n);
}
}
return 0;
}