Skip to content

Efficient way to set a json object as value into another json key #1406

@ibc

Description

@ibc

I've a function somewhere that creates and returns a json data object, and I want to use such a json data as value into the "data" key of another json response object.

Currently I'm doing something like this, and just wonder whether there is a way to avoid the data copy:

json response = json::object();

response["id"] = this->id;
response["data"] = this->foo.GetJsonData(); // This produces a `json`.

this->DoSomethingWith(response);

I expect there is no magic here and the json data returned by foo.GetJsonData() is being mem copied into response["data"]. May be I should, instead, do something like this?:

json response = json::object();

response["id"] = this->id;

// Allocate empty object for "data" key:
response["data"] = json::object();

// Get iterator to "data" object:
auto dataIterator = response.find("data"); 

// Pass the iterator to `foo.GetJsonData()` so it adds its keys/values into it.
this->foo.GetJsonData(dataIterator);

this->DoSomethingWith(response);

Then, void Foo::GetJsonData(json::iterator dataIterator) would do something like:

(*dataIterator)["foo"] = "FOO";
(*dataIterator)["bar"] = 1234;

Does it make any sense?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions