Search code examples
jsonjsoncpp

How to access the key of a jsoncpp Value


I kind of feel stupid for asking this, but haven't been able to find a way to get the key of a JSON value. I know how to retrieve the key if I have an iterator of the object. I also know of operator[]. In my case the key is not a known value, so can't use get(const char *key) or operator[]. Also can't find a getKey() method.

My JSON looks like this:

{Obj_Array: [{"122":{"Member_Array":["241", "642"]}}]}

For the piece of code to parse {"122":{"Member_Array":["241", "642"]}} I want to use get_key()-like function just to retrieve "122" but seems like I have to use an iterator which to me seems to be overkill.

I might have a fundamental lack of understanding of how jsoncpp is representing a JSON file.


Solution

  • First, what you have won't parse in JsonCPP. Keys must always be enclosed in double quotes:

    {"Obj_Array": [{"122":{"Member_Array":["241", "642"]}}]}

    Assuming that was just an oversight, if we add whitespace and tag the elements:

    {
    root->  "Obj_Array" : [
      elem0->   {
        key0->    "122":
        val0->       {
          key0.1->      "Member_Array" :
            val0.1->    [
              elem0.1.0->  "241",
              elem0.1.1->  "642" ]
                      }
                }
           ]
    }
    

    Assuming you have managed to read your data into a Json::Value (let's call it root), each of the tagged values can be accessed like this:

         elem0     = root[0];
         val0      = elem0["122"]
         val0_1    = val0["Member_Array"];
         elem0_1_0 = val0_1[0];
         elem0_1_1 = val0_1[1];
    

    You notice that this only retrieves values; the keys were known a priori. This is not unusual; the keys define the schema of the data; you have to know them to directly access the values.

    In your question, you state that this is not an option, because the keys are not known. Applying semantic meaning to unknown keys could be challenging, but you already came to the answer. If you want to get the key values, then you do have to iterate over the elements of the enclosing Json::Value.

    So, to get to key0, you need something like this (untested):

        elem0_members = elem0.getMemberNames();
        key0          = elem0_members[0];
    

    This isn't production quality, by any means, but I hope it points in the right direction.