简体   繁体   English

使用Python解析JSON嵌套字典

[英]Parsing JSON nested Dictionary using Python

I have the following nested Dictionary in JSON. 我在JSON中有以下嵌套字典。 If I want to get "id", "self", "name", how should I parse it using a Python Program. 如果我想获得“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
  }
}

To understand how your json is set up, it's easier to break it down. 要了解您的json是如何设置的,更容易将其分解。 Let's look at the first dictionary's keys, and remove the values. 让我们看看第一个字典的键,并删除值。

json = {"items": [], "links": {}}

You have a dictionary with two keys and two values. 你有一个包含两个键和两个值的字典。 All three of the variables you are looking for (id, self, name) are in the first key, "items". 您要查找的所有三个变量(id,self,name)都在第一个键“items”中。 So let's dive deeper. 让我们深入了解。

json["items"] = [{'links': {'self': 'https://www.google.com'}, 'name': 'beast', 'type': 'Device', 'id': '12345'}]

Now you have a list containing a dictionary with the values you are looking for, so let's enter the first and only value of the list containing the next dictionary. 现在您有一个包含字典的列表,其中包含您要查找的值,所以让我们输入包含下一个字典的列表的第一个也是唯一的值。

json["items"][0] = {'links': {'self': 'https://www.google.com'}, 'id': '12345', 'type': 'Device', 'name': 'beast'}

Finally we have the dictionary with the values are looking for, so you can use this code to find name and id. 最后我们得到了值正在寻找的字典,因此您可以使用此代码来查找名称和ID。

json["items"][0]["name"] = beast

json["items"][0]["id"] = 12345

The self variable is hidden one dictionary deeper so we have to delve into the links key. 自变量隐藏了一个更深的字典,所以我们必须深入研究链接键。

json["items"][0]["links"]["self"] = http://google.com

Now you have all of your values, you just need to follow through all the lists and dictionaries to get the value you want. 现在你拥有了所有的价值观,你只需要通过所有的列表和词典来获得你想要的价值。

It helps to write the dictionary indented, to better view its nesting: 它有助于编写字典缩进,以更好地查看其嵌套:

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
    }
}

Now you can extract what you want: 现在你可以提取你想要的东西:

If I want to get "id", "self", "name", 如果我想得到“id”,“self”,“name”,

print(mydict['items'][0]['id'])
print(mydict['items'][0]['links']['self'])
print(mydict['links']['self'])
print(mydict['items'][0]['name'])

You can write a function, that will get the values you need: 您可以编写一个函数,它将获得您需要的值:

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']

You can as well call any key that you want: 你也可以调用你想要的任何键:

data 数据

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
  }
}

Your json basically contains lists inside it. 你的json基本上包含里面的列表。 Jsons are accessed as key value pairs and lists are accessed using indexes. Jsons作为键值对进行访问,并使用索引访问列表。

json_object['items'][0]['id']

The above statement should give you the id. 上面的陈述应该给你id。 We are accessing the key items, which contains a list. 我们正在访问包含列表的关键项。 We have [0] because this list contains only one element (which is again a key value pair). 我们有[0]因为这个列表只包含一个元素(它也是一个键值对)。

The same approach is followed for self and name 对于self和name,遵循相同的方法

json_object['links']['self']
json_object['items'][0]['links']['self']
json_object['items'][0]['name']

The difference between accessing the two different 'self' bring that one is enclosed in a list hence we need to get into the list and the other one is a dictionary with key 'self' which is inside a dictionary 'links' 访问两个不同的“self”之间的区别使得一个被包含在列表中,因此我们需要进入列表而另一个是带有键'self'的字典,它位于字典'links'中

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

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