转换 json 值会导致 std::domain_error

Casting of json value results in std::domain_error

我正在尝试遍历 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;
        }
    }
}

如您所见,我首先尝试使用整数,因为这可能是更常用的类型。但是,我无法将从 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": [
   ]
}

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

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)