Syntax
import jsonExamples
Converting Python to JSON
Serializing a Python dictionary into a JSON-formatted string.
import json
data = {
"name": "Fola",
"age": 21,
"skills": ["Python", "TypeScript", "React"]
}
json_string = json.dumps(data)
print(json_string)
# {"name": "Fola", "age": 21, "skills": ["Python", "TypeScript", "React"]}
pretty = json.dumps(data, indent=2)
print(pretty) # nicely formatted with indentationParsing JSON
Converting a JSON string back into native Python objects.
import json
json_string = '{"name": "Zain", "age": 22, "active": true}'
data = json.loads(json_string)
print(data["name"]) # Zain
print(type(data)) # <class 'dict'>
print(data["active"]) # True (JSON true becomes Python True)Reading and Writing JSON Files
Working with JSON data stored in files directly.
import json
data = {"project": "DevNexus", "version": "1.0"}
with open("config.json", "w") as f:
json.dump(data, f, indent=2)
with open("config.json", "r") as f:
loaded = json.load(f)
print(loaded)Handling Invalid JSON
Gracefully catching errors when parsing malformed JSON.
import json
bad_json = "{name: Fola}" # missing quotes around keys - invalid JSON
try:
data = json.loads(bad_json)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")Best practices
- Use json.dump()/json.load() when working directly with files, and json.dumps()/json.loads() when working with strings already in memory
- Wrap json.loads() in a try/except for json.JSONDecodeError when parsing data from an external or untrusted source
- Use the indent parameter with json.dumps() to produce human-readable output for config files or debugging
- Remember not every Python object is JSON-serializable by default (like datetime or custom classes) - convert them to strings or use a custom encoder first
At a glance
- Purpose
- Scripting and general-purpose applications
- File extension
- .py
- Runs in
- Python interpreter
- Usually used with
- Python standard library and packages
Specifications & further reading
Related Python documentation
import
The import statement brings code from another module or package into the current file, letting you reuse functions, classes, and variables defined elsewhere - whether from Python's standard library, a third-party package, or your own project files. Python offers several import styles: importing an entire module, importing specific names directly, and renaming imports with 'as' to avoid naming conflicts or shorten long module names.if __name__ == '__main__'
Every Python module has a built-in __name__ variable. When a file is run directly, __name__ is set to '__main__'; when the same file is imported into another module, __name__ is set to the module's actual name instead. The if __name__ == '__main__': guard lets you write code that only runs when the file is executed directly, not when it's imported elsewhere - essential for writing reusable modules that also work as standalone scripts.File Handling
Python's built-in open() function reads from and writes to files on disk. Using it with the 'with' statement (a context manager) ensures the file is automatically closed when the block ends, even if an error occurs - this is the recommended way to work with files. The mode argument controls behavior: 'r' for reading, 'w' for writing (overwriting), 'a' for appending, among others.os Module
The os module provides functions for interacting with the operating system - working with file paths, listing directory contents, creating and removing folders, and reading environment variables. Its os.path submodule (or the more modern pathlib alternative) handles cross-platform file path manipulation, so your code works correctly on Windows, macOS, and Linux without hardcoding path separators.
The import statement brings code from another module or package into the current file, letting you reuse functions, classes, and variables defined elsewhere - whether from Python's standard library, a third-party package, or your own project files. Python offers several import styles: importing an entire module, importing specific names directly, and renaming imports with 'as' to avoid naming conflicts or shorten long module names.if __name__ == '__main__'
Every Python module has a built-in __name__ variable. When a file is run directly, __name__ is set to '__main__'; when the same file is imported into another module, __name__ is set to the module's actual name instead. The if __name__ == '__main__': guard lets you write code that only runs when the file is executed directly, not when it's imported elsewhere - essential for writing reusable modules that also work as standalone scripts.File Handling
Python's built-in open() function reads from and writes to files on disk. Using it with the 'with' statement (a context manager) ensures the file is automatically closed when the block ends, even if an error occurs - this is the recommended way to work with files. The mode argument controls behavior: 'r' for reading, 'w' for writing (overwriting), 'a' for appending, among others.os Module
The os module provides functions for interacting with the operating system - working with file paths, listing directory contents, creating and removing folders, and reading environment variables. Its os.path submodule (or the more modern pathlib alternative) handles cross-platform file path manipulation, so your code works correctly on Windows, macOS, and Linux without hardcoding path separators.