Python JSON tricks: how to deal with JSONDecodeError
A trick you may not know yet
--
JSON (JavaScript Object Notation) is a standard data format that uses human-readable text to store and transmit data objects consisting of attribute-value pairs and array data types. It is a very common data format with a diverse range of applications, especially in web development.
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 json
module:
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 JSONDecodeError
error:
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.