Deserialize a JSON string into a Python object
This post will discuss how to deserialize a JSON string into a Python object.
1. Using json Library
The idea is to use the loads() function from the json library to parse a JSON string into a Python object. It raises JSONDecodeError if the JSON string is not valid.
|
1 2 3 4 5 6 7 8 9 |
import json if __name__ == '__main__': json_str = '{"name": "John", "age": 18}' obj = json.loads(json_str) print((obj['name'], obj['age'])) # ('John', 18) |
2. Using simplejson Library
Another simple option is to use the simplejson library, which offers significant performance advantages over the json library. You can use its loads() function to deserialize a string to a Python object. This function also raises the JSONDecodeError when the JSON string is not valid.
|
1 2 3 4 5 6 7 8 9 |
import simplejson if __name__ == '__main__': json_str = '{"name": "John", "age": 18}' obj = simplejson.loads(json_str) print((obj['name'], obj['age'])) # ('John', 18) |
3. Using ast module
Another plausible way is to use the ast.literal_eval for safely evaluating a string to a Python object. Here’s a working example:
|
1 2 3 4 5 6 7 8 9 |
import ast if __name__ == '__main__': json_str = '{"name": "John", "age": 18}' obj = ast.literal_eval(json_str) print((obj['name'], obj['age'])) # ('John', 18) |
4. Using requests Library
Finally, if you need to parse the response of an HTTP request, you may use the requests library, as shown below:
|
1 2 3 4 5 6 7 8 9 |
import requests if __name__ == '__main__': url = "https://jsonplaceholder.typicode.com/todos/1" obj = requests.get(url).json() print(obj) |
That’s all about deserializing a JSON string into a Python object.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)