I'm trying to parse the following JSON file in c++. I would like to iterate over the 'attributes' array and obtain the value of the string:'value' for a specific value of a string:'name' of that attribute object. For ex: I would like to parse this JSON file and obtain the 'value' for 'mass'.
{
"active": true,
"apiTier": 0,
"attributes": [
{
"description": "Given in the datasheet as '0.33 kg (0.73 lbm)'.",
"maximumValue": "",
"measurementUnit": "kg",
"minimumValue": "",
"name": "mass",
"productConfiguration": "base",
"value": "0.33"
},
{
"description": "",
"maximumValue": "",
"measurementUnit": "",
"minimumValue": "",
"name": "propellant-type",
"productConfiguration": "base",
"value": "hydrazine"
},
{
"description": "Given in the datasheet as 'Thrust/Steady State' and the specified value is also reported as '(0.05-0.230) lbf'.",
"maximumValue": "1.02",
"measurementUnit": "N",
"minimumValue": "0.22",
"name": "thrust",
"productConfiguration": "base",
"value": ""
}
]
I am trying to do this in C++ using rapidjson library to parse the JSON file. Below is my implementation for the parsing of the JSON file. What I would like to do is within the for loop, for a specific 'value' for a string 'name' (for ex: mass) obtain the other 'values' for string such as 'maximumValue', 'minimumValue', 'value' etc.
#include <fstream>
#include <sstream>
#include <string>
#include <rapidjson/document.h>
int main()
{
std::ifstream inputFile( "/path/to/json/file/" );
std::stringstream jsonDocumentBuffer;
std::string inputLine;
while ( std::getline( inputFile, inputLine ) )
{
jsonDocumentBuffer << inputLine << "\n";
}
rapidjson::Document config;
config.Parse( jsonDocumentBuffer.str( ).c_str( ) );
assert(config.IsObject());
const rapidjson::Value& attributes = config["attributes"];
assert(attributes.IsArray());
int counter = 0;
for (rapidjson::Value::ConstValueIterator itr = attributes.Begin(); itr != attributes.End(); ++itr)
{
const rapidjson::Value& attribute = *itr;
assert(attribute.IsObject()); // each attribute is an object
for (rapidjson::Value::ConstMemberIterator itr2 = attribute.MemberBegin(); itr2 != attribute.MemberEnd(); ++itr2)
{
std::cout << itr2->name.GetString() << " : " << itr2->value.GetString() << std::endl;
}
}
Edit 1: I found a solution on how to iterate over the attributes array and access each string and its value for each one of the objects in the attributes array. However, what I would like to do is obtain value of any string (Ex: 'maximumValue','minimumValue', 'Value') etc for a specific value (Ex: mass) of a string 'name'.