user7515195
user7515195

Reputation:

How can I parse such json dict?

I have a dict in json format and need to get all 'src' value from all dict. Dict is such format

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

I stuck with

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

Dont know how to use the for method in this case asdfsdfsdafsdafdsfdsfdsfdsfsdfsdafsadfsdafsdafsdafsadfs

Upvotes: 0

Views: 80

Answers (2)

saud
saud

Reputation: 708

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

src will store a list of all the values.

PS : You could pull off a one-liner too, but it would look really messy

Upvotes: 0

nempat
nempat

Reputation: 456

Say x is the dictionary you provided.

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

This would be the way to extract sources:

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

Upvotes: 1

Related Questions