0

I have been trying to parse some JSON data that contains nested objects such as below.

{"channels": {"route1": {"post1": "/opt/v1/route1"}, "route2": {"post2": "/opt/v1/route2"}, "route3": {"post3": "/opt/v1/route3"}}}

In order to get name string and values, my approach is to obtain a reference to each Value object and to parse them consecutively. Due to the nested object structure, I have to store the references into a container, such as STL stack, to get back to the right position. However, the problem is that there is no way to store the reference variable into the STL stack due to the data type of reference.

I also tried to make a structure that contains the Value instance reference variable, and define a structure pointer variable to store into an STL stack. But, when I tried to push a pointer variable into the stack. The program terminates.

Do you have any idea how to parse this kind of nested objects?

2 Answers2

0

Have a look at http://www.json.org/ and you will find there is a list of C++ JSON parsers which you can use to solve your problem.

They will all have some kind of Class definition which will help you with getting access to nested attributes.

Unless you have very specialized requirements, you probably don't want to write your own parser, as that is harder that is appears at first glance.

Soren
  • 14,402
  • 4
  • 41
  • 67
0
string josn="{\"channels\": {\"route1\": {\"post1\": \"/opt/v1/route1\"}, \"route2\": {\"post2\": \"/opt/v1/route2\"}, \"route3\": {\"post3\": \"/opt/v1/route3\"}}} ";
    rapidjson::Document doc;

    if (!doc.Parse<0>(josn.c_str()).HasParseError()) {

        rapidjson::Value& channels=doc["channels"];

        printf("parsed string=%s\n",doc["channels"]["route1"]["post1"].GetString());

    }else{
        printf("error parsing the json %zu\n",doc.GetErrorOffset());
    }
Jain
  • 854
  • 5
  • 15