Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, Json and string indices must be integers, not str

I am using Python, and I sent a request to a URL and received a reply using httplib2. The reply I got was in JSon, how do I access a specific parameter. What I have at the moment is:

resp, content = parser.request(access_token_uri, method = 'POST', body = params, headers =     headers)
raise Exception(content['access_token'])

and I get the error

string indices must be integers, not str

How do I do it?

Thanks

like image 497
Meir Avatar asked Apr 30 '12 21:04

Meir


People also ask

How do I fix list indices must be integers or slices not str in Python?

The Python "TypeError: list indices must be integers or slices, not str" occurs when we use a string instead of an integer to access a list at a specific index. To solve the error, use the int() class to convert the string to an integer, e.g. my_list[int(my_str)] .

How do I fix TypeError string indices must be integers?

You cannot access a value in a string using another string. To solve TypeError: string indices must be integers; we should reference our dictionary instead of “ele“. We can access elements in our dictionary using a string. This is because dictionary keys can be strings.

What does list indices must be integers or slices not list mean?

This type error occurs when indexing a list with anything other than integers or slices, as the error mentions. Usually, the most straightforward method for solving this problem is to convert any relevant values to integer type using the int() function.

How do you convert a string to a JSON object in Python?

Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.


1 Answers

Well if the response type is json and it comes in type str.

If you are running 2.4 of Python use simplejson if 2.6 use json:

import json
# Your code
  retdict = json.loads(content)

Then treat it like a dictionary.

accesstoken = retdict['access_token']
like image 169
IainS Avatar answered Nov 14 '22 22:11

IainS