溫馨提示×

python的json庫怎么使用

小億
94
2023-12-16 02:13:15
欄目: 編程語言

使用Python的json庫可以很方便地處理JSON數據。下面是一些使用json庫的常見操作:

  1. 導入json庫:
import json
  1. 將JSON字符串轉換為Python對象(字典或列表):
json_str = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_str)
print(data)  # 輸出:{'name': 'John', 'age': 30, 'city': 'New York'}
  1. 將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"}
  1. 從文件中讀取JSON數據:
with open('data.json', 'r') as file:
    data = json.load(file)
    print(data)
  1. 將數據寫入JSON文件:
data = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as file:
    json.dump(data, file)

這些是json庫的一些基本用法,可以根據具體需求進行更復雜的操作。更多詳細的用法可以查看官方文檔:https://docs.python.org/3/library/json.html

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女