Reputation: 1
I have this JSON:
[{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 183.26, "Year": 2002 }, {repeated struct across 3mb .json}]
I would like to store 'Country' values into a std::vector<string> countries;
but I don't know how (I want to count how many different countries are in my JSON). There is what I've done so far:
std::ifstream ifs("../data/data.json");
if (!ifs.is_open()) {
std::cerr << "Could not open file for reading!\n";
return EXIT_FAILURE;
}
IStreamWrapper isw(ifs);
Document doc;
doc.ParseStream(isw);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
doc.Accept(writer);
if (doc.HasParseError()){
std::cout << "Error : " << doc.GetParseError() << '\n' << "Offset : " <<
doc.GetErrorOffset() << '\n';
return EXIT_FAILURE;
}
Could please somebody help me about how to handle this information and, if you could, explain me how to save into a 2D array like this?:
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 183.26, "Year": 2002 }
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 198.736, "Year": 2003 }
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 200.069, "Year": 2004 }
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 223.737, "Year": 2005 }
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 235.731, "Year": 2006 }
{ "Country": "AFG", "Indicator": "NGDP_R", "Value": 267.177, "Year": 2007 }...
Upvotes: 0
Views: 891
Reputation: 533
Sample on how to iterate (json values that are array and object has iterators)
constexpr std::string_view stringJson = R"([ {"k1": "v1", "k2": "v2"}, {"k1": "v1", "k2": "v2"} ])";
rapidjson::Document documentJson; // Create root rapidjson object
documentJson.Parse( stringJson.data() );
if( documentJson.IsArray() == true ) // Yes, we know it is an array :)
{
for( const auto& itArray : documentJson.GetArray() ) // iterate array
{
if( itArray.IsObject() == true ) // They are all objects
{
for( const auto& itObject : itArray.GetObject() )
{
const auto& _name = itObject.name; // get name
const auto& _value = itObject.value; // get value
std::cout << _name.GetString() << " : " << _value.GetString() << "\n";// dump it
}
}
}
}
Here is one tutorial. Click on RapidJSON chapter
Upvotes: 1