JSON (JavaScript Object Notation) is a lightweight data interchange format that’s easy for humans to read and write, and easy for machines to parse and generate. Python provides excellent support for working with JSON data through its built-in json module.
# Your Python dictionary data = { "name": "John Doe", "age": 30, "city": "New York", "languages": ["Python", "JavaScript", "Go"], "is_employee": True, "details": { "title": "Developer", "experience": 5 } }
# Write to a file withopen("data.json", "w") as file: json.dump(data, file, indent=4)
The indent=4 parameter makes the output file nicely formatted with 4-space indentation.
Reading JSON from a File
Reading JSON data from a file is just as straightforward:
1 2 3 4 5 6 7 8 9
import json
# Read from a file withopen("data.json", "r") as file: loaded_data = json.load(file)
# Now you can work with the loaded data print(loaded_data["name"]) # Output: John Doe print(loaded_data["languages"][0]) # Output: Python
Error Handling
It’s good practice to include error handling when working with files:
1 2 3 4 5 6 7 8 9
import json
try: withopen("data.json", "r") as file: data = json.load(file) except FileNotFoundError: print("The file was not found.") except json.JSONDecodeError: print("The file does not contain valid JSON.")
Working with JSON Strings
Sometimes you might need to convert between JSON strings and Python objects:
# Convert JSON string back to Python object python_object = json.loads(json_string)
Preserving Order
By default, Python dictionaries preserve the insertion order (since Python 3.7). If you’re using an older version, you can use collections.OrderedDict: