Reading a JSON string | TypeError: string indices must be integers
You are never parsing the string to a dictionary (json object). Change data = mtext
to: data = json.loads(mtext)
You should also add global data
to the readText method
sometimes you need to use json.loads again.. this worked for me..
jsonn_forSaleSummary_string = json.loads(forSaleSummary) //still string
jsonn_forSaleSummary = json.loads(jsonn_forSaleSummary_string)
finally!! json
TypeError: string indices must be integers
means an attempt to access a location within a string using an index that is not an integer. In this case your code (line 18) is using the string "type"
as an index. As this is not an integer, a TypeError
exception is raised.
It seems that your code is expecting data
to be a dictionary. There are (at least) 3 problems:
- You are not decoding ("loading") the JSON string. For this you should use
json.loads(data)
in thereadText()
function. This will return the dictionary that your code expects elsewhere. data
is a global variable with value initialised to an empty string (""
). You can not modify a global variable within a function without first declaring the variable using theglobal
keyword.- The code builds a list by appending successive items to it, however, that list is not used elsewhere. It is printed after the definition of
_getCurrentOperator()
but this is before any processing has been done, hence it is still empty at that point and[]
is displayed. Moveprint(list)
tomhello()
after_getCurrentOperator()
. (BTW usinglist
as a variable name is not advised as this shadows the builtinlist
)
You can revise readText()
to this:
def readText():
global data
mtext=""
mtext = strJson.get()
mlabel2 = Label(myGui,text=mtext).place(x=180,y=200)
data = json.loads(mtext)