TypeError: string indices must be integers, not str // Trying to get the key value

I try to get the key to the value I'm returning with, but when I use a simple approach to just get the value of a specific key, I get an error: TypeError: string indices should be integers, not str

I also tried the .get () method, but it didn't work either. Can someone tell me what I am doing wrong?

>>> import urllib2 >>> url = 'http://192.168.250.1/ajax.app?SessionId=8ef05397-ef00-451a-bc1c-c0d61 5a4811d&service=getDp&plantItemId=1413' >>> response = urllib2.urlopen(url) >>> dict = response.read() >>> dict '{"service":"getDp","plantItemId":"1413","value":" 21.4","unit":"\xc2\xb0C"}' >>> dict['value'] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: string indices must be integers, not str 
+5
source share
2 answers

It seems that "dict" is a variable of type string, not a dictionary. You must parse the string into a suitable dictionary format (e.g. JSON). Here is the code that will solve this problem:

 import json json_string = response.read() dict = json.loads(json_string) 

Now, for dict['value'] you will get what you need.

+5
source

response.read() returns an object of type string , not a dictionary, and you can index a string using only integer indices, and therefore you get your error.

You need to parse this string and convert it to a dictionary. To convert a dictionary string to a dictionary, you can do this:

 import ast dict = ast.literal_eval(dict) print dict['value'] 

Tried this on my machine with Python 2.7 and it works.

+4
source

Source: https://habr.com/ru/post/1246054/


All Articles