我正在尝试迭代json文件中的数组,以检索具有ID的条目。我想要比较的值不是字符串( json默认类型),而是一个uint64_t。出于测试目的,我写了这个简化的示例:
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main ()
{
std::string file = "test.json";
std::ifstream ifs(file);
json j = json::parse(ifs);
std::string s = "10";
int i = 10;
for (auto it : j["inputs"]) {
std::cout << "value: " << it["id"] << std::endl;
if (it["id"] == s) {
std::cout << "matching" << std::endl;
}
if (it["id"].get<int>() == i) {
std::cout << "also matching numeric" << std::endl;
}
}
}正如您所看到的,我首先尝试使用int类型,因为这可能是一种更常用的类型。但是,我无法将从ID字段获得的值转换为任何其他类型。我得到以下输出:
value: "10"
matching
terminate called after throwing an instance of 'std::domain_error'
what(): type must be number, but is string
Abgebrochen (Speicherabzug geschrieben)我想知道我必须做些什么才能将json的条目正确地转换为任意数据类型。谢谢!
测试json:
{
"inputs": [
{
"type": "camera",
"id": "10"
},
{
"type": "lidar",
"stream_id": "20"
}
],
"outputs": [
]
}发布于 2021-06-02 01:47:41
您使用的是什么版本?因为我得到了最新版本的下一个输出:
value: 10
also matching numeric
value: null
terminate called after throwing an instance of 'nlohmann::detail::type_error'
what(): [json.exception.type_error.302] type must be number, but is null
Aborted (core dumped)https://stackoverflow.com/questions/67793080
复制相似问题