Python處理JSON數據的方法有以下幾種:
import json
# 解碼JSON數據
json_str = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_str)
print(data) # 輸出:{'name': 'John', 'age': 30, 'city': 'New York'}
# 編碼Python對象為JSON數據
data = {'name': 'John', 'age': 30, 'city': 'New York'}
json_str = json.dumps(data)
print(json_str) # 輸出:{"name": "John", "age": 30, "city": "New York"}
import requests
url = 'https://api.example.com/data'
response = requests.get(url)
data = response.json()
print(data)
import pandas as pd
# 從JSON文件讀取數據
data = pd.read_json('data.json')
print(data)
# 從JSON字符串讀取數據
json_str = '[{"name": "John", "age": 30}, {"name": "Amy", "age": 25}]'
data = pd.read_json(json_str)
print(data)
這些是Python處理JSON數據的常用方法,根據具體的需求選擇適合的方法進行處理。