Closed
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.