首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在std::domain_error中转换JSON值的结果

在std::domain_error中转换JSON值的结果
EN

Stack Overflow用户
提问于 2021-06-02 01:00:12
回答 1查看 113关注 0票数 0

我正在尝试迭代json文件中的数组,以检索具有ID的条目。我想要比较的值不是字符串( json默认类型),而是一个uint64_t。出于测试目的,我写了这个简化的示例:

代码语言:javascript
复制
#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字段获得的值转换为任何其他类型。我得到以下输出:

代码语言:javascript
复制
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:

代码语言:javascript
复制
{
   "inputs": [
      {
         "type": "camera",
         "id": "10"
      },
      {
         "type": "lidar",
         "stream_id": "20"
      }
   ],
   "outputs": [
   ]
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-02 01:47:41

您使用的是什么版本?因为我得到了最新版本的下一个输出:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67793080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档