[英]Read & Parse a JSON file c++ BOOST
由于对此已经有很多问题,我有点担心要问...但是
我看过许多不同的问题,但这些问题中没有任何一项对我有用。 我将这段代码作为尝试,但是没有用:
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/json_parser.hpp"
using namespace boost::property_tree;
...
std::ifstream jsonFile("test_file.json");
if (!jsonFile){
std::cerr << "Error opening file\n";
return -1;
}
ptree pt;
json_parser::read_json(jsonFile, pt);
for (auto& array_element : pt) {
for (auto& property : array_element.second) {
std::cout << property.first << " = " << property.second.get_value<std::string>() << "\n";
}
}
其内容具有以下格式:
[{"number": 1234,"string": "hello world"}, {"number": 5678,"string": "foo bar"}, ... etc }]
我无法读取1234
,然后hello world
。 实际上,它什么也没做。 如何从.JSON
文件中读出?
我不确定是什么问题。 似乎有效(一旦使JSON有效):
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/json_parser.hpp"
int main() {
using boost::property_tree::ptree;
std::ifstream jsonFile("input.txt");
ptree pt;
read_json(jsonFile, pt);
for (auto & array_element: pt) {
for (auto & property: array_element.second) {
std::cout << property.first << " = " << property.second.get_value < std::string > () << "\n";
}
}
}
随着input.txt
包含:
[{"number": 1234, "string": "hello world"},{"number": 5678, "string": "foo bar"}]
版画
number = 1234
string = hello world
number = 5678
string = foo bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.