Eug*_*ene 4 json nested exists python-2.7
在下面的JSON响应中,检查python 2.7中是否存在嵌套键"C"的正确方法是什么?
{
  "A": {
    "B": {
      "C": {"D": "yes"}
         }
       }
}
一行JSON {"A":{"B":{"C":{"D":"是"}}}}}
这是一个老问题和接受的答案,但我会使用嵌套的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
或者如果你知道你总是有'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