我想遍历 json 对象中的每个条目,但是我一个接一个地收到一个难以理解的错误。如何更正以下示例?
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
void bla(std::string a) {
std::cout << a << '\n';
}
int main() {
json RecentFiles;
RecentFiles["1"]["Name"] = "test1.txt";
RecentFiles["1"]["Last modified"] = "monday";
RecentFiles["1"]["Score"] = 5.0f;
RecentFiles["2"]["Name"] = "test2.txt";
RecentFiles["2"]["Last modified"] = "tuesday";
RecentFiles["2"]["Score"] = 5.0f;
for (auto it = RecentFiles.begin(); it != RecentFiles.end(); ++it) {
bla("JSON: Recent file = " + it.value()["Name"]);
}
std::cout << RecentFiles; }
错误:
prog.cc: In function 'int main()':
prog.cc:18:31: error: invalid conversion from 'const char*' to 'nlohmann::detail::iter_impl<nlohmann::basic_json<> >::difference_type {aka long int}' [-fpermissive]
std::cout << it["Name"];
^
In file included from prog.cc:2:0:
./nlohmann/json.hpp:4418:15: note: initializing argument 1 of 'nlohmann::detail::iter_impl<BasicJsonType>::reference nlohmann::detail::iter_impl<BasicJsonType>::operator[](nlohmann::detail::iter_impl<BasicJsonType>::difference_type) const [with BasicJsonType = nlohmann::basic_json<>; nlohmann::detail::iter_impl<BasicJsonType>::reference = nlohmann::basic_json<>&; nlohmann::detail::iter_impl<BasicJsonType>::difference_type = long int]'
reference operator[](difference_type n) const
^
以上是在沙箱中完成的
https://wandbox.org/permlink/LNck7Gktm14bmPy0
这不是我正在使用的实际代码,我只是想看看我是否能理解如何使用 JSON 完成各种基本的事情。
目前我了解得很少,以至于我不知道我所做的事情是否本质上是正确的,但只是因为一些愚蠢的事情而中断,或者我是否在做一些根本错误的事情。