次の JSON 応答で、ネストされたキー「C」が Python 2.7 に存在するかどうかを確認する適切な方法は何ですか?
{
"A": {
"B": {
"C": {"D": "yes"}
}
}
}
1 行の JSON { "A": { "B": { "C": {"D": "yes"} } } }
次の JSON 応答で、ネストされたキー「C」が Python 2.7 に存在するかどうかを確認する適切な方法は何ですか?
{
"A": {
"B": {
"C": {"D": "yes"}
}
}
}
1 行の JSON { "A": { "B": { "C": {"D": "yes"} } } }
これは受け入れられた回答を持つ古い質問ですが、代わりにネストされた 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
モジュールを使用しjson
て入力を解析します。次に、try ステートメント内で、解析された入力からキー「A」を取得し、結果からキー「B」を取得し、その結果からキー「C」を取得しようとします。エラーがスローされた場合、ネストされた「C」は存在しません
私は単純な再帰的な解決策を使用しました:
def check_exists(exp, value):
# For the case that we have an empty element
if exp is None:
return False
# Check existence of the first key
if value[0] in exp:
# if this is the last key in the list, then no need to look further
if len(value) == 1:
return True
else:
next_value = value[1:len(value)]
return check_exists(exp[value[0]], next_value)
else:
return False
このコードを使用するには、ネストされたキーを文字列の配列に設定するだけです。次に例を示します。
rc = check_exists(json, ["A", "B", "C", "D"])