我从一个网站下载了JSON数据,我想从嵌套的JSON中选择特定的键:值。我将JSON转换为Python字典。然后我使用字典推导式来选择嵌套的键:值,然而有太多的嵌套,我相信有比分别展开每个字典更好的方法。我在我的方法中看到了冗余。你能提出更好的方法吗?
{
"success": true,
"payload": {
"tag": {
"slug": "python",
"name": "Python",
"postCount": 10590,
"virtuals": {
"isFollowing": false
}
},
"metadata": {
"followerCount": 18053,
"postCount": 10590,
"coverImage": {
"id": "1*O3-jbieSsxcQFkrTLp-1zw.gif",
"originalWidth": 550,
"originalHeight": 300
}
}
}
}
我的方法:
从datetime模块导入datetime和timedelta类。
import json,re
data=r'data.json'
#reads json and converts to dictionary
def js_r(data):
with open(data, encoding='Latin-1') as f_in:
return json.load(f_in)
def find_key(obj, key):
if isinstance(obj, dict):
yield from iter_dict(obj, key, [])
elif isinstance(obj, list):
yield from iter_list(obj, key, [])
def iter_dict(d, key, indices):
for k, v in d.items():
if k == key:
yield indices + [k], v
if isinstance(v, dict):
yield from iter_dict(v, key, indices + [k])
elif isinstance(v, list):
yield from iter_list(v, key, indices + [k])
def iter_list(seq, key, indices):
for k, v in enumerate(seq):
if isinstance(v, dict):
yield from iter_dict(v, key, indices + [k])
elif isinstance(v, list):
yield from iter_list(v, key, indices + [k])
if __name__=="__main__":
my_dict=js_r(data)
print ( "This is dictionary for python tag",my_dict)
keys=my_dict.keys()
print ("This is the dictionary keys",my_dict.keys())
my_payload=list(find_key(my_dict,'title'))
print ("These are my payload",my_payload)
my_post=iter_dict(my_dict,'User','id')
print(list(my_post))