Python JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format widely used for data exchange between a server and a web application. Python provides built-in support for JSON encoding and decoding through the json
module.
1. Encoding JSON
You can convert Python objects into JSON strings using the json.dumps()
function.
Example:
import json
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
json_string = json.dumps(person)
print(json_string) # Output: {"name": "Alice", "age": 30, "city": "New York"}
2. Decoding JSON
You can convert JSON strings into Python objects using the json.loads()
function.
Example:
json_string = '{"name": "Bob", "age": 25, "city": "London"}'
person = json.loads(json_string)
print(person["name"]) # Output: Bob
3. Reading JSON from a File
You can read JSON data from a file and parse it into Python objects using the json.load()
function.
Example:
with open("data.json", "r") as file:
data = json.load(file)
print(data)
4. Writing JSON to a File
You can write Python objects to a JSON file using the json.dump()
function.
Example:
data = {
"name": "Charlie",
"age": 35,
"city": "Paris"
}
with open("data.json", "w") as file:
json.dump(data, file)
Conclusion
Python’s json
module provides easy-to-use functions for encoding and decoding JSON data, making it simple to exchange data between Python and other applications or services that use JSON.