How do I convert a rapidjson array iterator to a rapidjson::value?
I do not want answers that focus on how to get the contents of a rapid json array, or how to iterate through it.
I am also very aware that I can access members through the iterator using the example in the rapidjson documentation itr->name
, but that is not what I want either. That form of working with rapidjson arrays already appears on many stack overflow questions and the rapidjson docs, and has been covered.
I need to end up with a rapidjson::value
when starting with a rapidjson array iterator.
If we have an std::vector<int>
than we can assign
std::vector<int>::iterator itMyInt = myvector.begin();
const int & myInt = *itMyInt;
I would expect to be able to do the same thing with a rapidjson array iterator, but my compiler disagrees.
The reason I need a rapidjson::value is that I'd like to reuse the same parsing method to parse the json object when is an element of an array, as I would when parsing that object on its own and not in an array.
Let me demonstrate with my minimal example:
// Rapid JSON Includes
#include <rapidjson/Document.h>
#include <rapidjson/StringBuffer.h>
#include <rapidjson/writer.h>
// Standard Includes
#include <exception>
#include <string>
#include <sstream>
//--------------------------------------------------------------------------------------------------
// NOTE -This stub cannot change
void ParseCar(const rapidjson::Value & carJson)
{
}
//--------------------------------------------------------------------------------------------------
int main()
{
std::string json =
"{"
" \"cars\" : ["
" {"
" \"name\" : \"Fiat\","
" \"price\" : 19.95"
" },"
" {"
" \"name\" : \"FRS\","
" \"price\" : 19995.00"
" }]"
"}";
// Parse the JSON
rapidjson::Document document;
document.Parse(json.c_str());
if (document.HasParseError())
{
// Error - Failed to parse JSON
std::ostringstream msg;
msg << "There was an error parsing the JSON"
<< " Error Code: " << document.GetParseError()
<< " Error Offset: " << document.GetErrorOffset();
throw std::exception(msg.str().c_str());
}
// Cars array
if (!document.HasMember("cars") ||
!document["cars"].IsArray())
{
std::string msg("Expected \"cars\" JSON array");
throw std::exception(msg.c_str());
}
const rapidjson::Value & carsArrayJSON = document["cars"];
/* Doesn't compile - No GetArray method exists
for (auto & carJSON : carsArrayJSON.GetArray())
{
}
*/
for (rapidjson::Value::ConstMemberIterator itCarJSON = carsArrayJSON.MemberBegin(); itCarJSON != carsArrayJSON.MemberEnd(); ++itCarJSON)
{
// Error - const rapidjson::GenericMember<Encoding,Allocator>' to 'const rapidjson::Value
const rapidjson::Value & carJSON = *itCarJSON;
ParseCar(carJSON);
}
return 0;
}