Processing JSON Data with Python: Parsing and Generating JSON
This article explains what JSON format is, introduces Python's built‑in json module, and provides step‑by‑step code examples for converting JSON strings to Python objects and serializing Python data structures back to JSON strings.
JSON (JavaScript Object Notation) is a lightweight data‑exchange format widely used in web applications because it is easy for humans to read and write and simple for machines to parse.
Python includes a built‑in json module that offers two main functions: json.loads() to parse a JSON‑formatted string into a Python object, and json.dumps() to serialize a Python object into a JSON string.
Parsing JSON Data
Given a JSON string such as:
<code>{
"name": "Lucy",
"age": 18,
"sex": "female",
"address": {
"province": "Guangdong",
"city": "Shenzhen"
},
"hobbies": ["reading", "traveling", "listening to music"],
"is_student": true
}</code>You can convert it to a Python object with:
<code>import json
json_str = '{"name": "Lucy", "age": 18, "sex": "female", "address": {"province": "Guangdong", "city": "Shenzhen"}, "hobbies": ["reading", "traveling", "listening to music"], "is_student": true}'
json_obj = json.loads(json_str)
print(json_obj)</code>The output is a Python dictionary that can be accessed like any other object.
Generating JSON Data
To create a JSON string from a Python dictionary, use json.dumps() :
<code>import json
data = {
'name': 'Tom',
'age': 20,
'sex': 'male',
'address': {
'province': 'Guangdong',
'city': 'Shenzhen'
},
'hobbies': ['reading', 'traveling', 'listening to music']
}
json_str = json.dumps(data)
print(json_str)</code>The resulting string is a valid JSON representation of the original Python data.
Conclusion
Python's built‑in json module makes it straightforward to parse JSON data into native Python objects and to serialize Python data structures back to JSON, providing essential support for any scenario that requires JSON handling.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.