Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to add json to another json? #1718

Closed
TrueWodzu opened this issue Aug 22, 2019 · 2 comments
Closed

How to add json to another json? #1718

TrueWodzu opened this issue Aug 22, 2019 · 2 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@TrueWodzu
Copy link

TrueWodzu commented Aug 22, 2019

Hi,

I am struggling a little when trying to add one json to another. Let me explain:

FramePickingResult PickFrame(int current_frame_number)
{
	if (current_frame_number > frames.back())
		return FramePickingResult::Abort;
	if (current_frame_number == frames[frame_index])
	{
		++frame_index;
		return FramePickingResult::Pick;
	}
	else
		return FramePickingResult::Skip;
}

std::optional<nlohmann::json> B()
{
	nlohmann::json result;
	result["B"] = {
		{ "SomeOtherObject", 34578}
	};
	return result;
};

std::optional<nlohmann::json> C()
{
	nlohmann::json result;
	result["C"] = {
		{ "Name", "Mark"}
	};
	return result;
};


int main(int argc, char* argv[])
{
	nlohmann::json json;
	json["Profiles"] = {};
	if (auto json_b = B())
	{
		// Add this to "Profiles"
	}

	if (auto json_c = C())
	{
		// Add this to "Profiles"
	}
}

{ "Profiles" : { "B" : { "SomeOtherObject: : 34578 }, "C" : { "Name" : "Mark" } } }

How can I achieve that? I would like to avoid using initializer list, thanks.
EDIT: To be honest I don't even know how to construct this with initializer list ;)

@TrueWodzu
Copy link
Author

I think I've figured it out, is this an optimal way?

int main(int argc, char* argv[])
{
	nlohmann::json json;
	json["Profiles"] = {};
	if (auto json_b = B())
	{
		json["B"] = json_b.value()["B"];
	}

	if (auto json_c = C())
	{
		json["C"] = json_c.value()["C"];
	}
}

@nlohmann
Copy link
Owner

You may want to use the update function instead:

int main(int argc, char* argv[])
{
    nlohmann::json json;
    json["Profiles"] = {};
    if (auto json_b = B())
    {
        json.update(json_b.value());
    }
    
    if (auto json_c = C())
    {
        json.update(json_c.value());
    }
    
    std::cout << json << std::endl;
}

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Aug 27, 2019
@nlohmann nlohmann closed this as completed Sep 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

2 participants