Skip to content

Instantly share code, notes, and snippets.

@NeroBurner
Last active August 13, 2019 13:36
Show Gist options
  • Save NeroBurner/40057865cd3068b9ed2d06604c3e19c6 to your computer and use it in GitHub Desktop.
Save NeroBurner/40057865cd3068b9ed2d06604c3e19c6 to your computer and use it in GitHub Desktop.
rapidjson::Pointer not working in loop
// external libraries
#include "rapidjson/document.h"
#include "rapidjson/pointer.h"
// standard libraries
#include <iostream>
#include <string>
#include <vector>
void parse_json_int(rapidjson::Document &json, const std::string &pointer, int &target)
{
if (rapidjson::Value *obj = rapidjson::Pointer(pointer.c_str()).Get(json))
{
if (obj->IsInt())
{
target = obj->GetInt();
} else
{
throw std::runtime_error(
std::string("parse_json: ")
+ "key '" + pointer + "' cannot be parsed as "
+ "int");
}
}
}
int main(int, char**)
{
// prepare Document
rapidjson::Document d;
d.Parse("{\"sp\":[1,2]}");
// directly give path to integer values
int val1, val2;
parse_json_int(d, "/sp/0", val1);
parse_json_int(d, "/sp/1", val2);
std::cout << "direct readout val1: " << val1 << std::endl;
std::cout << "direct readout val2: " << val2 << std::endl;
std::cout << std::endl;
{
std::vector<int> target;
std::string pointer = "/sp";
if (rapidjson::Value *obj = rapidjson::Pointer(pointer.c_str()).Get(d))
{
if (obj->IsArray())
{
const rapidjson::Value &array = obj->GetArray();
size_t size = array.Size();
// reserve memory
target.reserve(array.Size());
for (size_t i=0; i<array.Size(); i++) {
const std::string indexed_ptr = pointer + "/" + std::to_string(i);
int elem;
parse_json_int(d, indexed_ptr, elem);
target.push_back(elem);
}
} else
{
throw std::runtime_error(
std::string("parse_json: ")
+ "key '" + pointer + "' is not an array");
}
}
// output
std::cout << "std::vector<int> readouts" << std::endl;
for (size_t i=0; i<target.size(); i++)
{
std::cout << "/sp/"<< i << ": " << target[i] << std::endl;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment