jsonpython-2.7nestedexists

Find if nested key exists in json python


In the following JSON response, what's the proper way to check if the nested key "C" exists in python 2.7?

{
  "A": {
    "B": {
      "C": {"D": "yes"}
         }
       }
}

one line JSON { "A": { "B": { "C": {"D": "yes"} } } }


Solution

  • Use the json module to parse the input. Then within a try statement try to retrieve key "A" from the parsed input then key "B" from the result and then key "C" from that result. If an error gets thrown the nested "C" does not exists