Question

Background: I want to represent a deep hierarchy using JSON. I.e A Job has nodes, nodes have CPUs, CPUs have device loops and loops have devices. My data is on a database. I am using the visitor pattern to call back VisitJob, VisitNode, VisitCPU as I navigate, depth first the database.

I track the current parent wObject using a stack. I have added the top level and prepare an array for the Nodes. A Node's JSON is added, then I get called back to add that Node's CPUs.

The problem seems to be this: I have already done push.back for the Node object, but want to add more nested content. The CPUs' content does not appear in the final string.

Should it be possible to add more content to an object (I have its pointer) after it has been pushed back to its parent?

Was it helpful?

Solution

I assume you are referring to the json-spirit library that is here: https://github.com/cierelabs/json_spirit (which is the one the Spirit examples are based on).

Calling push_back will return a reference to the json::value object in the array. You can then continue to modify that object (via the reference).

json::value some_list;

json::value my_object = json::construct(
  "{"
  "   \"foo\"  : 42    ,"
  "   \"bar\"  : 498.5 ,"
  "   \"bork\" : [null,23,false]"
  "}"
  );

json::value& object = some_list.push_back(my_object);

object["sub"] = json::construct("[ {\"id\": 1}, {\"id\": 2} ]");

std::cout << some_list << std::endl;

which will result in:

[{"bar":498.5, "bork":[null, 23, false], "foo":42, "sub":[{"id":1}, {"id":2}]}]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top