I am trying to iterate over an array in a json file to retrieve an entry with an ID. The value that I want to compare it to is not a string (the json default type), but an uint64_t. For testing purposes, I wrote this simplified example:
#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;
}
}
}
As you can see, I tried using ints first, because that is probably a more commonly used type. However, I am unable to cast the value I get from the ID-field to any other type. I get the following output:
value: "10"
matching
terminate called after throwing an instance of 'std::domain_error'
what(): type must be number, but is string
Abgebrochen (Speicherabzug geschrieben)
I would like to know what I have to do to correctly cast entries of the json to an arbitrary data type. Thanks!
The test json:
{
"inputs": [
{
"type": "camera",
"id": "10"
},
{
"type": "lidar",
"stream_id": "20"
}
],
"outputs": [
]
}
What version are you using? Because I got next output on latest version:
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)