c++jsonjsoncpp

Jsoncpp nested arrays of objects


I need to search for an element in a json file using the jsoncpp library. I can't wrap my head around how to get to the most inner array... Any thoughts?

{
    "key": int,
    "array1": [
        {
            "key": int,
            "array2": [
                {
                    "key": int,
                    "array3": [
                        {
                            "needed_key": int
                        }
                    ]
                }
             ]
          }
     ]
}

Up until now I tried something like this:

    const Json::Value& array1 = root["array1"];
    for (size_t i = 0; i < array1.size(); i++)
    {
        const Json::Value& array2 = array1["array2"];
        for (size_t j = 0; j < array2.size(); j++)
        {
            const Json::Value& array3 = array2["array3"];
            for (size_t k = 0; k < array3.size(); k++)
            {
                std::cout << "Needed Key: " << array3["needed_key"].asInt();
            }
        }
    }

But it throws:

JSONCPP_NORETURN void throwLogicError(String const& msg) {
  throw LogicError(msg);
}

Solution

  • You can't access array2 with array1["array2"], since array1 contains an array of objects, not an object, so you should get array2 with an index i, array1[i]["array2"] instead.

    The following code works for me:

      const Json::Value &array1 = root["array1"];
      for (int i = 0; i < array1.size(); i++) {
        const Json::Value &array2 = array1[i]["array2"];
        for (int j = 0; j < array2.size(); j++) {
          const Json::Value &array3 = array2[j]["array3"];
          for (int k = 0; k < array3.size(); k++) {
            std::cout << "Needed Key: " << array3[k]["needed_key"].asInt();
          }
        }
      }
    

    The output looks like:

    Needed Key: 4