Ajukilibodin
Ajukilibodin

Reputation: 35

TypeError: list indices must be integers, not str with JSON

Here is my code;

f = open("test.json")
data = json.load(f)
loadmain = data['response']['users']
loadurl = loadmain['url']
print loadurl

Here is the JSON file

{

  "meta": {
"status": 200,
"msg": "OK"
  },

  "response": {
"total_users": 23,
"users": [
  {
    "name": "test",
    "url": "http://testurl.com",
    "updated": 1378151341
  }
...
..
.

I am a Python beginner so any feedback on this method appreciated, I am sure the decoding of the URL is not done in the right way. Anyways, my main concern; I want a list of the "url"s from the JSON to display but I get the "TypeError: list indices must be integers, not str"

Any suggestions?

Upvotes: 2

Views: 4301

Answers (2)

David Maust
David Maust

Reputation: 8270

One option to retrieve a list of urls is using a list comprehension:

urls = [ user['url'] for user in loadmain ]

Upvotes: 2

Lorenzo Baracchi
Lorenzo Baracchi

Reputation: 1978

I suspect that the problem is in loadurl = asd['url']. (apart the unknown asd)

In the variable loadmain you have a list of arrays, thus you need to do something like:

for x in loadmain:
   loadurl = x['url']

Upvotes: 2

Related Questions