Python JSON
Python provides a built-in module called json
that allows you to work with JSON (JavaScript Object Notation) data. The json
module provides functions for both encoding Python objects into JSON and decoding JSON back into Python objects.
Here’s a brief overview of how you can work with JSON in Python:
- Encoding (Python object to JSON):
- Use the
json.dumps()
function to convert a Python object (such as a dictionary, list, or string) into a JSON-formatted string. - Example:python
- Use the
import json data = { 'name': 'John Doe', 'age': 30, 'city': 'New York' } json_string = json.dumps(data) print(json_string)
Decoding (JSON to Python object):
- Use the
json.loads()
function to convert a JSON-formatted string into a Python object (such as a dictionary, list, or string). - Example:python
import json json_string = '{"name": "John Doe", "age": 30, "city": "New York"}' data = json.loads(json_string) print(data['name'])
Working with JSON files:
- To read JSON data from a file, you can use the
json.load()
function. - To write JSON data to a file, you can use the
json.dump()
function. - Example:python
import json # Reading from a JSON file with open('data.json') as f: data = json.load(f) # Writing to a JSON file data = { 'name': 'John Doe', 'age': 30, 'city': 'New York' } with open('output.json', 'w') as f: json.dump(data, f)
These are just some of the basic operations you can perform with JSON in Python. The json
module provides more functions and options for handling JSON data, such as customizing serialization and deserialization, working with JSON arrays, and more. You can refer to the Python documentation for further details: JSON – Python documentation