Python JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. Python provides the json
module for working with JSON data. In this lesson, we will cover the basics of using JSON in Python.
JSON Syntax
JSON data is written as key-value pairs, similar to Python dictionaries. Keys are always strings, and values can be strings, numbers, arrays, or objects. For example:
{
"name": "Alice",
"age": 30,
"city": "New York"
}
Using the json Module
The json
module in Python provides functions for encoding and decoding JSON data. To parse JSON data into a Python object, use the json.loads()
method. For example:
import json
# JSON data as a string
json_data = '{"name": "Alice", "age": 30, "city": "New York"}'
# Parse JSON data into a Python dictionary
parsed_data = json.loads(json_data)
print(parsed_data['name']) # Output: 'Alice'
Encoding JSON
To convert a Python object into a JSON string, use the json.dumps()
method. For example:
import json
# Python dictionary
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Convert to JSON string
json_data = json.dumps(data)
print(json_data) # Output: '{"name": "Alice", "age": 30, "city": "New York"}'
Conclusion
JSON is a popular data format for exchanging data between systems. Python's json
module provides functions for working with JSON data, allowing you to easily parse JSON data into Python objects and convert Python objects into JSON strings.