简体   繁体   English

有没有办法在python中只打印带有json键的数据?

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

im trying to print a json 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"} }, {

but i've run into an issue some of the json data doent have the key while some do i have written this thus far但是我遇到了一个问题,一些 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'])

But i get an error since the first element of the json file doesn't have the "ok" key但我收到一个错误,因为 json 文件的第一个元素没有“ok”键

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

Answer:回答:

You can use the get function of a dictionary:您可以使用字典的 get 函数:

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

So my_value will contain the existing value, or a default value you define in case there key doesn't exist in the dictionary所以my_value将包含现有值,或者您定义的默认值,以防字典中不存在键

You can also check if a key exists with an if:您还可以使用 if 检查密钥是否存在:

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

Extra tip:额外提示:

  • Make sure you anem your variables as descriptible as possible.确保您的变量尽可能可描述。 So for field in fields ..., for attribute in my_dictionary ...因此for field in fields ..., for attribute in my_dictionary ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM