Key Takeaways
- JSON is universal, human-readable data format
- Python’s
json
module handles JSON operations efficiently.- Adhere to JSON’s strict rules (double quotes, no trailing commas).
- Manage encoding and errors to ensure robust JSON handling.
- Essential for APIs, configs, and data storage in modern development.
Overview
JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format, independent of programming languages. It structures data using key-value pairs, making it human-readable and machine-parse able.
Basic JSON structure: Example:
{
"name": "Alice",
"age": 25,
"skills": ["Python", "JavaScript", "SQL"],
"is_active": true
}
JSON vs Python Dictionary
JSON and Python dictionaries share similarities but differ in key aspects.
Feature | JSON | Python Dictionary |
---|---|---|
Keys | Must be strings | Any hashable type |
Quotes | Double quotes only | Single or double quotes |
Booleans | true , false | True , False |
Null values | null | None |
Trailing commas | Not allowed | Allowed |
Valid JSON Rules
JSON adheres to strict formatting unlike YAML’s behavior which can vary with different versions and evolving specifications.
- Data Types:
- Strings (double-quoted)
- Numbers (integer/float)
- Booleans (
true
/false
) null
- Objects (key-value pairs)
- Arrays (ordered lists)
- Key Rules:
- Strings must use double quotes.
- Trailing commas are prohibited.
- Comments are not allowed.
- Keys must be strings.
{
"valid_string": "Hello World",
"valid_number": 42,
"valid_boolean": true,
"valid_null": null,
"valid_array": [1, 2, 3],
"valid_object": {"nested": "value"}
}
Reading and Writing JSON in Python
Python’s json
module provides four core functions:
- For Strings:
json.loads()
: Converts JSON string to Python object.json.dumps()
: Converts Python object to JSON string.
- For Files:
json.load()
: Reads JSON from a file.json.dump()
: Writes JSON to a file.
Examples
Reading JSON:
import json
# From string
json_string = '{"name": "Bob", "age": 30}'
data = json.loads(json_string)
print(data["name"]) # Output: Bob
# From file
with open('data.json', 'r') as file:
data = json.load(file)
Writing JSON:
import json
# To string
data = {"name": "Charlie", "age": 35}
json_string = json.dumps(data, indent=2)
print(json_string)
# To file
with open('output.json', 'w') as file:
json.dump(data, file, indent=2)
The indent
parameter enhances readability by adding whitespace.
Common Errors and Best Practices
-
Encoding Issues: Specify
encoding='utf-8'
for files with non-ASCII characters.with open('data.json', 'r', encoding='utf-8') as file: data = json.load(file)
-
Common Mistakes:
-
Trailing commas: JSON disallows them, unlike Python dictionaries.
# Invalid JSON bad_json = '{"name": "Alice", "age": 25,}' # Valid dictionary in Python good_dict = {"name": "Alice", "age": 25,}
-
Quote types: JSON requires double quotes.
# Invalid JSON bad_json = "{'name': 'Alice'}" # Valid JSON good_json = '{"name": "Alice"}'
-
Applications of JSON
JSON is prevalent in:
REST APIs:Â Data exchange between services
Configuration files:Â Application settings
Inter-service communication:Â Microservices messaging
Data storage:Â NoSQL databases (MongoDB)