Python JSON tricks: how to deal with JSONDecodeError
A JSON looks like the dictionary type in Python, but they are different. The essential difference is that a JSON is a pure string that has a strict format. If you don’t write it properly, you may have unexpected errors.
In this statement,
student_dict is a valid Python dictionary, but it is not a JSON. To convert a Python dictionary to a JSON, you can use the
dumps method of the
You can also convert a JSON to a Python dictionary using the
loads method of the
json module. You should be careful when you read the JSON from some file or manually write the JSON.
Trick 1: You should use double quotes for keys and values, otherwise you will have the
To solve this error, you need to change the double quotes for the keys and values. You can you single quotes or triple single/double quotes for the whole string, and use double quotes for the keys and values. Alternatively, you can use double quotes for the whole string, and escape the double quotes for the keys and values with a slash, which is mandatory in Java.