JSON is not a package you install with pip — it’s a built-in module in Python, so no installation is needed. You can use it immediately by importing json in any Python 2.6+ or 3.x environment.
Background
JavaScript Object Notation (JSON) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It was originally derived from JavaScript but is now language-independent and widely used for configuration files, API responses, and data storage across web services, mobile apps, and desktop software. Python has included native support for JSON since version 2.6 through the json module, which provides functions to encode Python objects into JSON strings and decode JSON strings back into Python data structures like dictionaries and lists.
How It Works
The json module in Python’s standard library includes four primary functions:
json.dumps()— serializes a Python object into a JSON-formatted stringjson.dump()— writes a Python object directly to a file-like object in JSON formatjson.loads()— parses a JSON string into a Python objectjson.load()— reads and parses JSON from a file-like object
These functions handle data types like strings, numbers, booleans, null, lists, and dictionaries. Complex types such as dates or custom objects require serialization logic (e.g., using a custom encoder) since JSON has no native representation for them.
How to Choose
You don’t choose whether to install JSON — you choose how to use it. If you’re working with external APIs (like GitHub, Twitter, or weather services), you’ll typically receive JSON responses and need to decode them. If you’re saving application settings or user preferences locally, you might encode Python dictionaries into JSON files. For most use cases, the built-in json module is sufficient. Third-party libraries like ujson or orjson exist for performance-critical applications, but they require installation via pip and are rarely necessary for typical projects.
Common Problems
Even though JSON is built-in, users often encounter issues:
- TypeError: Object of type ‘datetime’ is not JSON serializable — JSON doesn’t support Python’s
datetimeobjects. Fix by converting them to strings first:json.dumps(my_date.isoformat()) - ValueError: Expecting property name enclosed in double quotes — JSON requires double quotes for keys and strings; single quotes are invalid. Python dictionaries use single quotes, but
json.dumps()automatically converts them. - File not found when using json.load() — ensure the file path is correct and the file exists. Use
os.path.exists()to verify before opening. - UnicodeDecodeError — if reading a file with non-UTF-8 encoding, specify the encoding:
open('file.json', 'r', encoding='utf-8')
Comparisons
While the built-in json module is reliable and sufficient for most applications, alternatives exist for specialized needs:
- ujson — a C-based library that’s significantly faster for large datasets. Install with
pip install ujson. - orjson — even faster, supports more types (like bytes and UUIDs), and outputs UTF-8 by default. Install with
pip install orjson. - yaml — often used for configuration files; more human-readable but not JSON. Requires
pyyaml. - xml — older standard for structured data; verbose and slower than JSON.
For 95% of use cases, stick with the standard library. Only switch if profiling shows JSON parsing is a bottleneck — such as in high-throughput web servers or data pipelines processing millions of records per minute.
Costs
There is no cost to use the built-in json module. It requires no installation, has no dependencies, and consumes minimal system resources. Third-party alternatives like ujson or orjson are free to use under open-source licenses (BSD, MIT), but they add external dependencies to your project, which can complicate deployment in restricted environments (e.g., corporate networks, Docker containers with minimal base images).
Safety
Never use json.loads() on untrusted input without validation. Maliciously crafted JSON can cause denial-of-service attacks by including deeply nested structures or extremely large numbers, leading to excessive memory or CPU usage. Python’s built-in parser has protections against stack overflow, but you should still:
- Set a reasonable maximum size limit on incoming JSON payloads
- Use
json.loads(data, max_allowable_depth=10)if available (not standard, but some libraries support it) - Validate schema using libraries like
jsonschemaafter parsing
Also, avoid using eval() on JSON strings — even though it might seem like a quick workaround, it’s a severe security risk and can execute arbitrary code.
Alternatives
While JSON is the most common format for data interchange, other formats serve different purposes:
- YAML — preferred for configuration files due to its readability and support for comments. Uses
pyyaml. - XML — used in legacy enterprise systems and SOAP APIs. Heavier but supports namespaces and complex schemas.
- Protocol Buffers (protobuf) — binary format from Google; faster and smaller than JSON. Requires schema definition and code generation.
- MessagePack — compact binary serialization format, faster than JSON, supported in many languages.
- CSV — simple tabular data; not hierarchical, so unsuitable for nested objects.
For web APIs, JSON remains the de facto standard due to universal browser support and simplicity. For high-performance internal systems, consider binary formats. For human-editable configs, YAML is often better.
Frequently Asked Questions
Do I need to install json with pip?
No. The json module is part of Python’s standard library and comes pre-installed with every Python 2.6+ and 3.x distribution. You only need to import it with import json.
Why does my code say ‘No module named json’?
This error typically means you’re using an extremely old or custom Python build (pre-2.6) that lacks the standard library. Upgrade to Python 3.7 or later, which is the current standard. If you’re in a minimal container (like Alpine Linux), ensure you installed the full Python package, not just the minimal runtime.
Can I use json with Python 2.7?
Yes. Python 2.7 has full support for the json module. However, Python 2 reached end-of-life in January 2020. All new projects should use Python 3.9 or later for security, performance, and compatibility reasons.
What’s the difference between json.dumps() and json.dump()?
dumps() returns a string; dump() writes directly to a file. Use dumps() when you need the JSON as a variable in memory; use dump() when you want to save it to a file. Both convert the same Python objects.
Why does my JSON file look different when I open it in a text editor?
By default, json.dumps() outputs compact JSON with no whitespace. To make it readable, add indent=4: json.dumps(data, indent=4). This adds line breaks and indentation for human viewing, though it increases file size slightly.
Is JSON faster than reading a Python pickle file?
No. Pickle is faster and more feature-rich for Python-specific data, but it’s insecure and not interoperable. JSON is slower but safer and readable across platforms. Use pickle only for internal, trusted Python-to-Python serialization. For data exchange, stick with JSON.