3

As per the tutorial:

Each JSON value is stored in a type called Value. A Document, representing the DOM, contains the root Value of the DOM tree.

If so, it should be possible to make a sub-document from a document.

If my JSON is:

{
    "mydict": {
        "inner dict": {
            "val": 1,
            "val2": 2
        }
    }
}

I'd like to be able to create a Document from the inner dictionary.

(And then follow the instructions in the FAQ for How to insert a document node into another document?)

Josh Olson
  • 397
  • 2
  • 15
dWitty
  • 494
  • 9
  • 22
  • I don't think it's possible to do so but why do you want to do it? – Asesh Jul 03 '17 at 10:30
  • I would like to be able to insert some complex values into a non-root position in a complex true, recursively. The allocator for the root is not happy being used for adding things in non-root positions, and only Documents have GetAllocator. – dWitty Jul 03 '17 at 10:43
  • ya but you can use that allocator in rapidjson iterators and values – Asesh Jul 03 '17 at 10:52

1 Answers1

3

Given the original document contains:

{
    "mydict": {
        "inner dict": {
            "val": 1,
            "val2": 2
        }
    }
}

You can copy the sub-document:

const char json[] = "{\"mydict\": {\"inner dict\": {\"val\": 1, \"val2\": 2}}}";
Document doc, sub; // Null
doc.Parse(json);
sub.CopyFrom(doc["mydict"], doc.GetAllocator());

You can also swap the sub-document with another:

const char json[] = "{\"mydict\": {\"inner dict\": {\"val\": 1, \"val2\": 2}}}";
Document doc, sub; // Null
doc.Parse(json);
sub.Swap(doc["mydict"]);

With some validation:

const char json[] = "{\"mydict\": {\"inner dict\": {\"val\": 1, \"val2\": 2}}}";
Document doc, sub; // Null
doc.Parse(json);
if (doc.IsObject()) {
    auto it = doc.FindMember("mydict");
    if (it != doc.MemberEnd() && it->value.IsObject()) {
        sub.Swap(it->value);
    }
}

Each will result in sub containing:

{
    "inner dict": {
        "val": 1,
        "val2": 2
    }
}

With the CopyFrom() approach, doc will contain:

{
    "mydict": {
        "inner dict": {
            "val": 1,
            "val2": 2
        }
    }
}

With Swap():

{
    "mydict": null
}
Josh Olson
  • 397
  • 2
  • 15