我怎么解析这样的json dict?

时间:2017-11-26 14:10:11

标签: python json parsing dictionary

我有一个json格式的字典,需要从所有字典中获取所有' src' 值。 Dict就是这样的格式

{
  "response": {
    "165": {
      "photo": {
        "access_key": "25b928f75a3730a988", 
        "created": 1490195550, 
        "text": "", 
        "sizes": [
          {
            "src": "https://pp.userapi.com/xxxxx.jpg", 
            "height": 133, 
            "type": "p", 
            "width": 200
          }, 
        ], 
        "pid": 456239362, 
        "aid": -3, 
        "owner_id": 14793
      }, 
      "type": "photo"
    }, 
      "78": {
      "photo": {
        "access_key": "2cc06244975d01b54c", 
        "created": 1501701707, 
        "text": "", 
        "sizes": [
          {
            "src": "https://pp.userapi.com/xxxxx.jpg", 
            "height": 412, 
            "type": "p", 
            "width": 200
          }, 
        ], 
        "pid": 456239726, 
        "aid": -3, 
        "owner_id": 14793
      }, 
      "type": "photo"
    }
  }
}

我坚持

photos = json.load(open('photos.json'))['response']

在这种情况下,不知道如何使用 for 方法 asdfsdfsdafsdafdsfdsfdsfdsfsdfsdafsadfsdafsdafsdafsadfs

2 个答案:

答案 0 :(得分:2)

Say x是您提供的字典。

x = json.load(open('photos.json'))['response']

这将是提取资源的方法:

sizes = [x[elem]['photo']['sizes'] for elem in x]
srcs = []
for size_list in sizes:
    for size_element in size_list:
        srcs.append(size_element['src'])

答案 1 :(得分:1)

photos = json.load(open('photos.json'))['response']
src = [i['photo']['sizes'][0]['src'] for i in photos.values()]

src将存储所有值的列表。

PS :你也可以推出单线,但看起来很麻烦