Python has a built-in json module for working with JSON data. Here are the common approaches:
import json
# Read JSON file
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
import json
json_string = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_string)
print(data['name']) # Output: John
import json
import urllib.request
# Using urllib (built-in)
with urllib.request.urlopen('https://api.example.com/data') as response:
data = json.load(response)
# Or with requests library (if installed)
import requests
response = requests.get('https://api.example.com/data')
data = response.json()
| Function | Use Case |
|---|---|
json.load(file) | Read JSON from a file object |
json.loads(string) | Parse JSON from a string |
# Handle potential errors
import json
try:
with open('data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
except FileNotFoundError:
print("File not found")
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
encoding='utf-8' for files with special characterstry/except blocks to handle malformed JSON gracefullySign in to post your answer