英文:
nlohmann-json: add something to json object
问题
我有这个JSON文件:
{
"user1" : {
"sell" : [
{ "id":1001, "name" : "some name1", "price" : 100, "available" : 10, "category" : "xxx"},
{ "id":1002, "name" : "some name2", "price" : 200, "available" : 10, "category" : "xyz"}
],
"buy" : [
{ "id":2001, "name" : "some name4", "price" : 100, "available" : 10, "category" : "jkdhsajdh"},
{ "id":2002, "name" : "some name7", "price" : 200, "available" : 10, "category" : "dasdasfjk"}
]
},
"user2" : {
"sell" : [
{ "id":403049, "name" : "some name1", "price" : 100, "available" : 10, "category" : "xxx"},
{ "id":434432, "name" : "some name2", "price" : 200, "available" : 10, "category" : "xyz"}
],
"buy" : [
{ "id":32144, "name" : "some name4", "price" : 100, "available" : 10, "category" : "jkdhsajdh"},
{ "id":5244, "name" : "some name7", "price" : 200, "available" : 10, "category" : "dasdasfjk"}
]
}
}
我不知道如何向data["user1"]["buy"]
中添加一些项目:
std::ifstream f(argv[1]);
json data = json::parse(f);
那么我该如何向data["user1"]["buy"]
中添加一些内容?
英文:
I've got this json file:
{
"user1" : {
"sell" : [
{ "id":1001, "name" : "some name1", "price" : 100, "available" : 10, "category" : "xxx"},
{ "id":1002, "name" : "some name2", "price" : 200, "available" : 10, "category" : "xyz"}
],
"buy" : [
{ "id":2001, "name" : "some name4", "price" : 100, "available" : 10, "category" : "jkdhsajdh"},
{ "id":2002, "name" : "some name7", "price" : 200, "available" : 10, "category" : "dasdasfjk"}
]
},
"user2" : {
"sell" : [
{ "id":403049, "name" : "some name1", "price" : 100, "available" : 10, "category" : "xxx"},
{ "id":434432, "name" : "some name2", "price" : 200, "available" : 10, "category" : "xyz"}
],
"buy" : [
{ "id":32144, "name" : "some name4", "price" : 100, "available" : 10, "category" : "jkdhsajdh"},
{ "id":5244, "name" : "some name7", "price" : 200, "available" : 10, "category" : "dasdasfjk"}
]
}
}
and I have no idea how to add some items to let's say data["user1"]["buy"]
std::ifstream f(argv[1]);
json data = json::parse(f);
so how can I add some stuff to data["user1"]["buy"]?
答案1
得分: 2
文档1指出,默认情况下,JSON 数组使用 std::vector
表示。因此,您可以简单地使用 push_back
。
当然,您首先需要将数据打包到另一个 JSON 对象中,然后再将其推送到数组中。
类似于以下方式(未经测试):
json newEntry;
newEntry["id"] = 2003;
newEntry["name"] = "另一个名称";
...
data["user1"]["buy"].push_back(newEntry);
英文:
The documentation says that JSON arrays are represented using std::vector
by default. Therefore, you can simply use push_back
.
Of course, you'll first have to pack your data into another JSON object before you push it into the array.
Something like this (untested):
json newEntry;
newEntry["id"] = 2003;
newEntry["name"] = "another name";
...
data["user1"]["buy"].push_back(newEntry);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论