Parse JSON file (C ++ Boost)
I would like to use the Boost (Property Tree) library to parse the following valid JSON file:
{
"user": {
"userID": "5C118C8D-AA65-49C0-B907-348DE87D6665",
"dateProperty": "05-06-2015"
},
"challenges": [
{
"question#1": "answer",
"value": 5
},
{
"question": "answer",
"value": 5
},
{
"question": "answer",
"value": 5
},
{
"question": "answer",
"value": 5
},
{
"question": "answer",
"value": 5
},
{
"question": "answer",
"value": 5
},
{
"question": "answer",
"value": 5
},
{
"question": "answer",
"value": 5
},
{
"question": "answer",
"value": 5
},
{
"question": "answer",
"value": 5
}
] }
I have verified that the JSON format is correct.
I have also consulted several sites such as:
- Boost 1.46.1, Property Tree: How to iterate through ptree to get sub ptrees?
- http://www.technical-recipes.com/2014/using-boostproperty_tree/
But I still haven't got the correct results. I would like to collect "user" and "problems" as key / value pairs. A better result would be to write the "problems" (question / answers) and user information (userID, dateProperty) to a std :: pair that can be written to std: map.
Any suggestions would be appreciated?
+3
source to share
1 answer
I think as usual you are just confused how ptree stores JSON arrays ?
Here's a quick demo:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
#include <fstream>
int main()
{
using namespace boost::property_tree;
ptree pt;
read_json(std::cin, pt);
for (auto& challenge : pt.get_child("challenges"))
for (auto& prop : challenge.second)
std::cout << prop.first << ": " << prop.second.get_value<std::string>() << "\n";
}
Printing
question#1: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
+2
source to share