4

次の JSON 応答で、ネストされたキー「C」が Python 2.7 に存在するかどうかを確認する適切な方法は何ですか?

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

1 行の JSON { "A": { "B": { "C": {"D": "yes"} } } }

4

4 に答える 4

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

または、常に「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
于 2015-09-19T19:24:53.200 に答える
1

モジュールを使用しjsonて入力を解析します。次に、try ステートメント内で、解析された入力からキー「A」を取得し、結果からキー「B」を取得し、その結果からキー「C」を取得しようとします。エラーがスローされた場合、ネストされた「C」は存在しません

于 2013-03-22T23:17:01.313 に答える
0

私は単純な再帰的な解決策を使用しました:

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"])
于 2021-06-18T11:26:13.363 に答える