共計 544 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 json
模塊來處理 JSON 數據。下面是一些常見的 json
庫的使用示例:
- 將 Python 對象轉換為 JSON 字符串:
import json
data = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
json_data = json.dumps(data)
print(json_data)
- 將 JSON 字符串轉換為 Python 對象:
import json
json_data = '{"name":"Alice","age": 25,"city":"New York"}'
data = json.loads(json_data)
print(data)
- 將數據寫入 JSON 文件:
import json
data = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
with open('data.json', 'w') as file:
json.dump(data, file)
- 從 JSON 文件中讀取數據:
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
這些是 json
庫的一些基本用法,你可以根據具體的需求進一步探索。
丸趣 TV 網 – 提供最優質的資源集合!
正文完