-2

I'm trying to read in a JSON file using C++. In the file i have key value pairs. And in the value, I am passing number of values with different parameters.

Is this approach is correct? Please suggest if there is any modifications required?

approach1:

"test_details" : {
        "testd" : "1",
        "testvalue":["one", "two(param1, para2)", "three(param1, param2, param3)"]
    }

approach2:

"test_details" : {
        "testd" : "1",
        "testvalue":"one"
    },
    {
        "testd" : "2",
        "testvalue":"two(param1, para2)"
    },
    {
        "testd" : "3",
        "testvalue":"three(param1, param2, param3)"
    }

Thank you

sara
  • 25
  • 3
  • 1
    it doesnt matter, that is the value of a json pair and is a string type... so you can parse it to a std string... – ΦXocę 웃 Пepeúpa ツ Feb 16 '21 at 14:35
  • It's not correct, it's not incorrect. Your approach is a design decision, which you could change if you wanted to. – john Feb 16 '21 at 14:37
  • post the code of how you are trying to parse that json – ΦXocę 웃 Пepeúpa ツ Feb 16 '21 at 14:38
  • Hi, Now we are designing how we can frame the JSON format/structure. Not yet started parsing the json format. I have update with original post with another approach. Can i proceed with any approach? – sara Feb 16 '21 at 14:47
  • The two structures are not equivalent. The second one has more information, like `"testd" : "2"`, which is not present in the first. – trincot Feb 16 '21 at 16:13

2 Answers2

0

the right way to parse that is to get the object under the key "testvalue" which you have to parse to a, lets say vector<string>

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Yes it is possible to parse that json into an object. I highly prefer the second approach. Say you go with the second approach, you can create a TestCase class that looks look like:

class TestCase {
public:
   std::string id; 
   std::string value; 
   // std::vector<std::string> values; // this will hold multiple values for one test case
}

class TestDetails { public: std::vector<TestCase> };

An object of this class can be constructed by deserializing your json payload. And vice versa to get the json serialization result.

Check this library for parsing json in C++. There are plenty of solutions for json parsing, the library I linked is a personal preference.

Oussama Ben Ghorbel
  • 2,132
  • 4
  • 17
  • 34