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

I have a vector of keys and and a string of value and i want to create nested json array #1604

Closed
arwinder-jaspal opened this issue May 21, 2019 · 2 comments

Comments

@arwinder-jaspal
Copy link

arwinder-jaspal commented May 21, 2019

Hi, I am trying to create a nested json array (the number or layers may vary depending on the input stream)
After some pre processing: This is my expected input and output
Sample data:
Keys: {a,b,c} Value: "Hi"
Keys: {a,b,d} Value: "Hi",

Expected Outcome: {"a":{"b":{"c":"Hi","d":"Hi"}}}
Current Outcome: [{"a":{"b":{"c":"Hi"}}},{"a":{"b":{"d":"Hi"}}}] //created 2 objects instead of one

  • Describe what you tried.
    My Code:
#include <nlohmann/json.hpp>

using json = nlohmann::json;
nlohmann::json createJsonObject(std::vector<std::string> key, std::string value)
{	
	nlohmann::json JsonObjects = nlohmann::json::object();
		for(int i =key.size()-1; i>=0; --i)
		{	
			if (i == key.size()-1)
			{
				JsonObjects[key[i]]=value;
			}	
			else
			{
				JsonObjects[key[i]]=JsonObjects;
				JsonObjects.erase(key[i+1]);	
			}	
		}
	return JsonObjects;
}

int main()
{		
	std::vector<std::string> key_vect1 ={"a", "b", "c"};
	std::vector<std::string> key_vect2 ={"a", "b", "d"};
	std::vector <std::vector<std::string>> key_array;
	key_array.push_back(key_vect1);
	key_array.push_back(key_vect2);
	std::string value ="Hi";
	std::string str_msg ="";
	
	auto JsonArrays = nlohmann::json::array();
	for(int j = 0; j<key_array.size();j++){
		nlohmann::json object = nlohmann::json::object();
		object = createJsonObject(key_array[j],value);
		JsonArrays.push_back(object);
		str_msg = JsonArrays.dump();
	}
	std::cout << str_msg << '\n';
}

Sorry, I am new to C++, and this code is just a test code I wrote to see if I am able to achieve this in C++.

Thank you in advance.

@arwinder-jaspal
Copy link
Author

	json j1;

	j1["a"]["b"]["c"] = "Hi";
	j1["a"]["b"]["d"] = "Hello";

My goal is to automate this.

@arwinder-jaspal
Copy link
Author

I manage to sort this out using merge_patch instead of push_back

Will close the issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant