What Is JSON and Why Parse It
JSON (JavaScript Object Notation) is a lightweight text-based data interchange format that has become the standard for transferring information between applications. Despite its name, JSON is language-independent and is widely used in all modern programming languages.
Key advantages of JSON:
- Human-readable format
- Simple data structure
- Universal support
- More compact than XML
Example of a JSON object:
{
"name": "Alice",
"age": 30,
"is_active": true,
"hobbies": ["reading", "cycling", "traveling"]
}
Python's Built-in json Module
Python provides a powerful built-in json module for working with JSON data. This module supports two main operations:
- Deserialization — converting a JSON string into Python objects
- Serialization — converting Python objects into a JSON string
To get started, import the module:
import json
Parsing a JSON String into Python Objects
Using json.loads()
The json.loads() function (load string) converts a JSON string into the corresponding Python object:
import json
json_data = '{"name": "Bob", "age": 25, "is_active": false}'
parsed_data = json.loads(json_data)
print(parsed_data) # {'name': 'Bob', 'age': 25, 'is_active': False}
print(type(parsed_data)) # <class 'dict'>
After parsing, you can work with the data like a regular dictionary:
print(parsed_data['name']) # Bob
print(parsed_data['age']) # 25
Data Type Mapping
JSON types are automatically converted to Python types:
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number | int/float |
| true/false | True/False |
| null | None |
Converting Python Objects to JSON
Using json.dumps()
The json.dumps() function converts Python objects into a JSON string:
data = {'name': 'Alice', 'age': 30, 'is_active': True}
json_string = json.dumps(data)
print(json_string) # {"name": "Alice", "age": 30, "is_active": true}
Formatting Options
Use additional parameters to improve readability:
data = {'name': 'Alice', 'age': 30, 'city': 'Moscow'}
json_pretty = json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False)
print(json_pretty)
Key parameters:
indent— indentation for formattingsort_keys— sort dictionary keysensure_ascii— support Unicode characters
Working with JSON Files
Reading JSON from a File
Use json.load() to read JSON data from a file:
with open('data.json', 'r', encoding='utf-8') as file:
content = json.load(file)
print(content)
Writing JSON to a File
The json.dump() function writes data to a file:
data = {'city': 'Moscow', 'temperature': -5, 'weather': 'snow'}
with open('weather.json', 'w', encoding='utf-8') as file:
json.dump(data, file, indent=4, ensure_ascii=False)
File Handling Best Practices
- Always specify the encoding