簡體   English   中英

有沒有辦法在python中只打印帶有json鍵的數據?

[英]Is there a way to print only the data with the json key in python?

我試圖在 python 中打印一個 json

 "rules":[ { "table":"Forest", "format":"List", "header":{"en":"Forest","fr":"Forêt"}, "fields":[ { "name":"Name", "displayName":{"en":"Forest","fr":"Forêt"} }, { "name":"ForestMode", "displayName":{"en":"Forest Mode","fr":"Mode forêt"}, "ok":"re.search('Windows(2019|2016)Forest',x) != None", "warn":"re.search('Windows(2012R2|2012)Forest',x) != None", "nok":"re.search('Windows(2008R2|2008|2003|2003Interim|2000)Forest',x) != None", "comment":{"en":"Increase the functional level of the forest","fr":"Augmenter le niveau fonctionnel de la forêt"} }, { "name":"RootDomain", "displayName":{"en":"Root Domain","fr":"Domaine racine"} }, { "name":"Domains", "displayName":{"en":"Domains","fr":"Domaines"} }, { "name":"Sites", "displayName":{"en":"Sites","fr":"Sites"} }, {

但是我遇到了一個問題,一些 json 數據沒有密鑰,而有些我已經寫了這個

 with open('./rules-adds.json', 'r') as ad_file: ad_data = json.load(ad_file) # print(ad_data) data = ad_data["rules"] # print(data) # print(json.dumps(ad_data, indent=4)) for x in data: print(x['table'], x['fields']) for y in x['fields']: print(y['name'])

但我收到一個錯誤,因為 json 文件的第一個元素沒有“ok”鍵

 print(y['ok']) KeyError: 'ok'

回答:

您可以使用字典的 get 函數:

my_value = my_dict.get('some_key_name', 'in_case_not_found')

所以my_value將包含現有值,或者您定義的默認值,以防字典中不存在鍵

您還可以使用 if 檢查密鑰是否存在:

if 'some_key_name' in my_dict:
    print(my_dict['some_key_name'])
else:
    print('Well, key is not there')

額外提示:

  • 確保您的變量盡可能可描述。 因此for field in fields ..., for attribute in my_dictionary ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM