Skip to content

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

Closed
@arwinder-jaspal

Description

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.

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions