what(): 没有这样的节点 json boost

问题描述

我正在尝试使用 boost::property_tree 解析以下 JSON 文件

{
    "pi": 3.141,"temp": 3.141,"happy": true,"name": "Niels","nothing": null,"answer": {
        "everything": 42
    },"list": [
        1,2
    ],"object": {
        "currency": "USD","value": 42.99
    }
}

但是对于第二个节点“temp”,它给出了一个错误-

terminate called after throwing an instance of 'boost::wrapexcept<boost::property_tree::ptree_bad_path>'
  what():  No such node (temp)
Aborted (core dumped)
@ubuntu:~/git_

编写如下代码-

std::ifstream file(jsonPath,std::ifstream::binary);
  using json = nlohmann::json;
  namespace pt = boost::property_tree;
  pt::ptree root;
  pt::read_json(jsonPath,root);  // Load the json file in this ptree 
  string valPi = root.get<string>("pi");  
  string valtemp = root.get<string>("temp"); 

解决方法

Boost 属性树不是 JSON 库。

如果你已经包含了 nlohmann::json,你为什么要(ab)使用它?

您的选择器路径可能与 JSON 不匹配。很难说,因为您展示的示例工作正常:

Live On Coliru

印刷品

{
    "pi": "3.141","temp": "3.141","happy": "true","name": "Niels","nothing": "null","answer": {
        "everything": "42"
    },"list": [
        "1","0","2"
    ],"object": {
        "currency": "USD","value": "42.99"
    }
}
Yay 3.141 and 3.141

没问题。

但是请注意,所有类型信息是如何丢失的,这只是触及 PropertyTree 中“限制”的表面:https://www.boost.org/doc/libs/1_75_0/doc/html/property_tree/parsers.html#property_tree.parsers.json_parser

使用 Boost JSON

认真起来:

#include <boost/json.hpp>
#include <iostream>

int main() {
    auto root = boost::json::parse(R"({
    "pi": 3.141,"temp": 3.141,"happy": true,"nothing": null,"answer": {
        "everything": 42
    },"list": [
        1,2
    ],"value": 42.99
    }
})");

    std::cout << root << "\n";
    auto valPi   = root.at("pi").get_double();
    auto valtemp = root.at("temp").get_double();

    std::cout << "Yay " << valPi << " and " << valtemp << "\n";
}

印刷品

{"pi":3.141E0,"temp":3.141E0,"happy":true,"name":"Niels","nothing":null,"answer":{"everything":42},"list":
[1,2],"object":{"currency":"USD","value":4.299E1}}
Yay 3.141 and 3.141

使用nlohmann::json

Live On Compiler Explorer

#include <nlohmann/json.hpp>
#include <iostream>

int main() {
    auto root = nlohmann::json::parse(R"({
    "pi": 3.141,"value": 42.99
    }
})");

    std::cout << root << "\n";
    auto valPi   = root["pi"].get<double>();
    auto valtemp = root["temp"].get<double>();

    std::cout << "Yay " << valPi << " and " << valtemp << "\n";
}

印刷品

{"answer":{"everything":42},"list":[1,"object":{"currency"
:"USD","value":42.99},"pi":3.141,"temp":3.141}
Yay 3.141 and 3.141