JSON
import json
# Create a Python dictionary
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# Encode the dictionary as JSON
json_data = json.dumps(data)
print(json_data)
Last updated
import json
# Create a Python dictionary
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# Encode the dictionary as JSON
json_data = json.dumps(data)
print(json_data)
Last updated
The `json.dumps()` function takes a Python object and converts it into a JSON string.import json
# JSON data as a string
json_data = '{"name": "John", "age": 30, "city": "New York"}'
# Decode JSON into a Python dictionary
data = json.loads(json_data)
print(data)
import json
# Read JSON data from a file
with open("data.json", "r") as file:
data = json.load(file)
print(data)
import json
# Python data to be written as JSON
data = {
"name": "Alice",
"age": 25,
"city": "San Francisco"
}
# Write JSON data to a file
with open("output.json", "w") as file:
json.dump(data, file)
import json
json_data = 'invalid json'
try:
data = json.loads(json_data)
except json.JSONDecodeError as e:
print("JSON decoding error:", e)