溫馨提示×

python的json庫怎么使用

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

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

  1. 導(dǎo)入json庫:
import json
  1. 將JSON字符串轉(zhuǎn)換為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對象轉(zhuǎn)換為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數(shù)據(jù):
with open('data.json', 'r') as file:
    data = json.load(file)
    print(data)
  1. 將數(shù)據(jù)寫入JSON文件:
data = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as file:
    json.dump(data, file)

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

0