Python provides a built-in package called json, which can be used to work with JSON data.
Convert dictionary to JSON
import json # Example of Python dictionary. employee = { "id" : 93423, "name" : "John", "city" : "Montréal" } # Convert to JSON. json_result = json.dumps(employee) # Print JSON. print(json_result)
Output
{"name": "John", "city": "Montr\u00e9al", "id": 93423}
Parse JSON string back to Python
import json # A JSON string. json_str = '{"city": "Montr\u00e9al", "id": 93423, "name": "John"}' # Convert JSON string to Python dictionary. emp = json.loads(json_str) # Access dictionary data. print(emp["id"]) print(emp["city"])
Output
93423 Montréal