[Solved] TypeError: string indices must be integers, not str

Have a problem

ExtendValue =  {
			"area": "1",
            "info": "{\"year\": 2014, \"a\": 12, \"b\": 3, \"c\":5}",
            "trip_country": "CN"

When accessing according to the dictionary, an error is reported. Typeerror: String indexes must be integers, not STR, which means that the index must be int type, not character type

Cause of error

There are many possibilities for this kind of mistake. I only record the mistakes I encounter

After searching, it is found that the error is caused by the JSON format, and the value of info is JSON data, which is not directly recognized by python


The original object stored in the dictionary is JSON, so you need to decode the JSON before you can read it

You need JSON. Loads () to convert the JSON format to a python recognized format

Add a line of code:



use of Python JSON modules dumps, dump, loads and load

JSON. Dumps format Python objects into JSON characters (convert dict to STR)


JSON. Loads decode the JSON string into a python object (convert STR into dict)
json_str = json.dumps(data)  
data = json.loads(json_str) 
JSON. Dump is mainly used to write Python objects to JSON files
f = open('demo.json','w',encoding='utf-8')
JSON. Load loads the JSON format file and returns the python object
f = open('demo.json','r',encoding='utf-8')
data = json.load(f)

Similar Posts: