Introduction
JSON (JavaScript Object Notation) is a widely used data format for data exchange. Python provides a built-in module called "json" that allows you to work with JSON data seamlessly. In this guide, we'll explore how to work with JSON data in Python, including parsing JSON, creating JSON, and manipulating JSON objects.
What is JSON?
JSON is a lightweight and text-based data interchange format. It is easy for humans to read and write and easy for machines to parse and generate. JSON data is represented as key-value pairs, where keys are strings, and values can be strings, numbers, objects, arrays, or even "null" and "true" or "false."
Using the "json" Module
The "json" module in Python provides functions to work with JSON data. Let's explore some common tasks using this module:
1. Parsing JSON Data
import json
# JSON data as a string
json_string = '{"name": "Alice", "age": 30, "city": "New York"}'
# Parse JSON string to a Python dictionary
data = json.loads(json_string)
# Accessing values
print("Name:", data["name"])
print("Age:", data["age"])
print("City:", data["city"])
2. Creating JSON Data
import json
# Creating a Python dictionary
person = {
"name": "Bob",
"age": 25,
"city": "San Francisco"
}
# Convert the dictionary to JSON format
json_string = json.dumps(person)
# Output the JSON string
print(json_string)
3. Working with JSON Arrays
import json
# JSON array as a string
json_array_string = '[{"name": "Carol", "age": 28}, {"name": "David", "age": 35}]'
# Parse JSON array
people = json.loads(json_array_string)
# Accessing values in the array
for person in people:
print("Name:", person["name"])
print("Age:", person["age"])
Conclusion
Working with JSON data in Python is a common and essential task, as it is widely used for data exchange between systems and applications. The "json" module provides a simple and effective way to parse, create, and manipulate JSON data. Mastering JSON handling in Python is a valuable skill for any Python developer.