使用Python解析JSON嵌套字典

时间:2018-08-10 14:21:32

标签: python json python-3.x dictionary data-structures

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

4 个答案:

答案 0 :(得分:2)

要了解您的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

现在您拥有了所有的价值,您只需要遵循所有列表和字典来获取所需的价值即可。

答案 1 :(得分:0)

它有助于缩进字典,以更好地查看其嵌套:

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

答案 2 :(得分:0)

您可以编写一个函数,该函数将获取所需的值:

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

答案 3 :(得分:0)

您的json基本上在其中包含列表。将Json作为键值对访问,并使用索引访问列表。

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

上面的语句应为您提供ID。我们正在访问包含列表的关键项。我们有[0],因为此列表仅包含一个元素(也是键值对)。

对自己和名字采用相同的方法

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

访问两个不同的“自我”之间的区别在于,一个被封装在列表中,因此我们需要进入列表,而另一个是在字典“链接”内部的具有键“自我”的字典。 / p>