2013-03-04 46 views
4

在下面的JSON響應中,檢查python 2.7中是否存在嵌套鍵「C」的正確方法是什麼?查找嵌套鍵是否存在於json python

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

一行JSON { 「A」:{ 「B」:{ 「C」:{ 「d」: 「是」}}}}

回答

1

使用json模塊解析輸入。然後在try語句中嘗試從解析的輸入中檢索關鍵字「A」,然後從結果中鍵入「B」,然後從結果中鍵入「C」。如果錯誤被拋出嵌套的「C」不存在

4

這是一個接受答案的老問題,但我會使用嵌套的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