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
Solutions
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:
ExtendValue["info"]=json.loads(ExtendValue["info"])
Expand
use of Python JSON modules dumps, dump, loads and load
JSON. Dumps
format Python objects into JSON characters (convert dict to STR)
format
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.dump(decode_json,f,ensure_ascii=False)
f.close()
JSON. Load
loads the JSON format file and returns the python object
f = open('demo.json','r',encoding='utf-8')
data = json.load(f)
print(data,type(data))
f.close()
Similar Posts:
- Python: How to Solve raise JSONDecodeError(“Expecting value”, s, err.value) from None json.decoder…
- Python TypeError: Object of type int64 is not JSON serializable
- TypeError: the JSON object must be str, not ‘bytes’
- Python JSON error json.decoder.jsondecodeerror Chinese
- Python: json:json.decoder.JSONDecodeError: Invalid control character at: line 2 column 18 (char 19)
- TypeError: Object of type ‘datetime‘ is not JSON serializable [Solved]
- [Solved] json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1:
- Django: How to Convert Models object to JSON