查找json python中是否存在嵌套键

Eug*_*ene 4 json nested exists python-2.7

在下面的JSON响应中,检查python 2.7中是否存在嵌套键"C"的正确方法是什么?

{
  "A": {
    "B": {
      "C": {"D": "yes"}
         }
       }
}
Run Code Online (Sandbox Code Playgroud)

一行JSON {"A":{"B":{"C":{"D":"是"}}}}}

Dan*_*son 5

这是一个老问题和接受的答案,但我会使用嵌套的if语句来做这件事.

import json
json = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')

if 'A' in json:
    if 'B' in json['A']:
        if 'C' in json['A']['B']:
            print(json['A']['B']['C']) #or whatever you want to do
Run Code Online (Sandbox Code Playgroud)

或者如果你知道你总是有'A'和'B':

import json
json = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')

if 'C' in json['A']['B']:
    print(json['A']['B']['C']) #or whatever
Run Code Online (Sandbox Code Playgroud)


Ant*_*hon 2

使用该json模块来解析输入。然后在 try 语句中尝试从解析的输入中检索键“A”,然后从结果中检索键“B”,然后从该结果中检索键“C”。如果抛出错误,则嵌套的“C”不存在