-1

I have a json data that i got from VK.

 {
"response": [{
    "id": 156603484,
    "name": "Equestria in the Space",
    "screen_name": "equestriaspace",
    "is_closed": 0,
    "type": "group",
    "is_admin": 1,
    "admin_level": 3,
    "is_member": 1,
    "description": "Официально сообщество Equestria in the Space!",
    "photo_50": "https://pp.userap...089/u0_mBSE4E34.jpg",
    "photo_100": "https://pp.userap...088/O6vENP0IW_w.jpg",
    "photo_200": "https://pp.userap...086/rwntMz6YwWM.jpg"
    }]
}

So i wanted to print only "name" but when i did it it gave me an error

TypeError: list indices must be integers or slices, not str

My code is:

method_url = 'https://api.vk.com/method/groups.getById?'
data = dict(access_token=access_token, gid=group_id)
response = requests.post(method_url, data)
result = json.loads(response.text)

print (result['response']['name'])

Any idea how can i fix it? In google i found how to parse json with one array. But here is two or something

P.S dont beat me so much. I am new in Python, just learning

Jengas
  • 204
  • 2
  • 11
  • 8
    `print (result['response'][0]['name'])`. `response` is a list with a dictionary at the 0th index. – roganjosh Jan 31 '18 at 22:36
  • 2
    Possible duplicate of [Access a particular field in arbitrarily nested JSON data](https://stackoverflow.com/questions/48193502/access-a-particular-field-in-arbitrarily-nested-json-data) – Aran-Fey Jan 31 '18 at 22:42

1 Answers1

1

What sort of data structure is the value of the key response?

i.e. how would you get it if I gave you the following instead?

"response": [{
  "id": 156603484,
  "name": "Equestria in the Space",
  "screen_name": "equestriaspace",
  "is_closed": 0,
  "type": "group",
  "is_admin": 1,
  "admin_level": 3,
  "is_member": 1,
  "description": "Официально сообщество Equestria in the Space!",
  "photo_50": "https://pp.userap...089/u0_mBSE4E34.jpg",
  "photo_100": "https://pp.userap...088/O6vENP0IW_w.jpg",
  "photo_200": "https://pp.userap...086/rwntMz6YwWM.jpg"
},
{
  "not_a_real_response": "just some garbage actually"
}]

You would need to pick out the first response in that array of responses. As nice people in the comments have already told you.

name = result['response'][0]['name']

Skam
  • 7,298
  • 4
  • 22
  • 31