Я пытаюсь добавить JSON объекты в файл в указанной позиции c, но я не могу сделать это как требуется. Я получаю результат, но без ",", разделяя значения, поэтому они являются отдельными JSON объектами.
Я хочу, чтобы l oop через JSON объектов и добавить результат в файл и отделить его с помощью "," и это действительный JSON. Вот что я попробовал
auto js_text = R"(
{
"a": "all_items",
"b": []
}
)";
std::ofstream js_file("test.json");
js_file << std::setw(4) << js_text << std::endl;
std::ifstream in("test4.json");
json js_file = json::parse(in);
std::ifstream load_url("url_file.json");
json url_file = json::parse(load_url);
for (auto& endpoint : url_file["url_list"])
{
std::string url = endpoint["url"].get<std::string>();
auto r = cpr::Get(cpr::Url{ url });
json j = json::parse(r.text); // r gets a nested json objects from parsed url
for (auto& td : j["b"])
{
json value = j["b"][0];
json data = js_file;
data["b"][0] = value;
std::ofstream output;
output.open("test.json",std::ios_base::app );
output << std::setw(4) << data << std::endl;
}
Результат, который я хочу получить:
{
"a": "all_items",
"b": [
{
"c": "xxx",
"d": "yyy"
},
{
"e": "zzz"
}
]
}
Обновленный код: после полезного ввода Ботье.
auto js_text = R"(
{
"a": "abc",
"b": [ ]
}
)";
json js_file = json::parse(js_text);
std::ifstream load_url("url_file.json");
json url_file = json::parse(load_url);
for (auto& endpoint : url_file["url_list"])
{
std::string url = endpoint["url"].get<std::string>();
auto r = cpr::Get(cpr::Url{ url });
json j = json::parse(r.text); // j contains results from multiple HTTP requests that has json objects.
for (auto& elem : j["b"])
{
json jd = j["b"];
js_file["b"].emplace_back(std::move(td));
std::cout << "jd:" << jd.dump(4) << std::endl;
}
}
std::ofstream output;
output.open("test.json",std::ios_base::app );
output << std::setw(4) << js_file << std::endl;
}
Надеюсь, что это поможет другим.