[英]Parsing JSON nested Dictionary using Python
我在JSON中有以下嵌套字典。 如果我想获得“id”,“self”,“name”,我应该如何使用Python程序解析它。
{
"items": [
{
"id": "12345",
"links": {
"self": "https://www.google.com"
},
"name": "beast",
"type": "Device"
}
],
"links": {
"self": "https://www.google.com"
},
"paging": {
"count": 1,
"limit": 1,
"offset": 0,
"pages": 1
}
}
要了解您的json是如何设置的,更容易将其分解。 让我们看看第一个字典的键,并删除值。
json = {"items": [], "links": {}}
你有一个包含两个键和两个值的字典。 您要查找的所有三个变量(id,self,name)都在第一个键“items”中。 让我们深入了解。
json["items"] = [{'links': {'self': 'https://www.google.com'}, 'name': 'beast', 'type': 'Device', 'id': '12345'}]
现在您有一个包含字典的列表,其中包含您要查找的值,所以让我们输入包含下一个字典的列表的第一个也是唯一的值。
json["items"][0] = {'links': {'self': 'https://www.google.com'}, 'id': '12345', 'type': 'Device', 'name': 'beast'}
最后我们得到了值正在寻找的字典,因此您可以使用此代码来查找名称和ID。
json["items"][0]["name"] = beast
json["items"][0]["id"] = 12345
自变量隐藏了一个更深的字典,所以我们必须深入研究链接键。
json["items"][0]["links"]["self"] = http://google.com
现在你拥有了所有的价值观,你只需要通过所有的列表和词典来获得你想要的价值。
它有助于编写字典缩进,以更好地查看其嵌套:
mydict = {
'items': [
{
'id': '12345',
'links': {'self': 'https://www.google.com'},
'name': 'beast',
'type': 'Device'
}
],
'links': {'self': 'https://www.google.com'},
'paging': {
'count': 1,
'limit': 1,
'offset': 0,
'pages': 1
}
}
现在你可以提取你想要的东西:
如果我想得到“id”,“self”,“name”,
print(mydict['items'][0]['id'])
print(mydict['items'][0]['links']['self'])
print(mydict['links']['self'])
print(mydict['items'][0]['name'])
您可以编写一个函数,它将获得您需要的值:
def dict_get(x,key,here=None):
x = x.copy()
if here is None: here = []
if x.get(key):
here.append(x.get(key))
x.pop(key)
else:
for i,j in x.items():
if isinstance(x[i],list): dict_get(x[i][0],key,here)
if isinstance(x[i],dict): dict_get(x[i],key,here)
return here
dict_get(a,'id')
['12345']
dict_get(a,'self')
['https://www.google.com', 'https://www.google.com']
dict_get(a,'name')
['beast']
你也可以调用你想要的任何键:
数据
a = {
"items": [
{
"id": "12345",
"links": {
"self": "https://www.google.com"
},
"name": "beast",
"type": "Device"
}
],
"links": {
"self": "https://www.google.com"
},
"paging": {
"count": 1,
"limit": 1,
"offset": 0,
"pages": 1
}
}
你的json基本上包含里面的列表。 Jsons作为键值对进行访问,并使用索引访问列表。
json_object['items'][0]['id']
上面的陈述应该给你id。 我们正在访问包含列表的关键项。 我们有[0]因为这个列表只包含一个元素(它也是一个键值对)。
对于self和name,遵循相同的方法
json_object['links']['self']
json_object['items'][0]['links']['self']
json_object['items'][0]['name']
访问两个不同的“self”之间的区别使得一个被包含在列表中,因此我们需要进入列表而另一个是带有键'self'的字典,它位于字典'links'中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.