【发布时间】:2019-03-30 12:41:54
【问题描述】:
我想遍历一个 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 完成各种基本的事情。
目前我了解的太少,以至于我不知道我所做的事情本质上是正确的,但只是因为一些愚蠢的事情而中断,还是我做的事情根本上是错误的。
【问题讨论】:
-
你遇到了什么错误?
-
我也尝试添加 .string() 。由于我将使用它来处理在 std::string 对象的其他函数中定义的复杂内容,因此我想将数据中的条目作为 std::string(而不是其他类型的字符串,如 string_t)获取。我只需要一个简单的循环来遍历所有条目,并允许我获取标准类中的内容
-
您是否尝试在 cstdlib 中使用 stringstream 或 atoi() 函数将“test1.txt”转换为 unsigned int ?也许你应该直接转换它,或者 JSON 头文件有问题。
-
我发现如果我使用 bla(it.value()["Name"].dump());然后我得到我想要得到的字符串,但用“”括起来。我现在要做一个简单的函数,再次删除那些 " 以便我可以继续,但感觉有点像这是一个 hack,而不是正确和可行的方法
-
顺便说一下,它是 wandbox 而不是沙箱,虽然后者非常适合上下文 ;-D
标签: c++ json nlohmann-json