一、JSON介紹
JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式,易于人閱讀和撰寫,
二、常用方法
| 方法 | 描述 |
|---|---|
| json.loads() | 將JSON字串轉化為Python物件 |
| json.dumps() | 將Python物件轉化為JSON字串 |
| json.load() | 讀取json檔案,把檔案中的json資料轉化為python資料型別 |
| json.dump() | 寫入json檔案,把python資料轉化成json資料寫入json檔案中 |
json.loads(),json.dumps(): 用來處理資料格式(json <==> python)
json.load(),json.dump(): 用于檔案操作(讀、寫)
三、使用
導包:
# python自帶json庫
import json
1.loads()
import json
a = "[{'name': '小明', 'age': 10}]"
# 將JSON字串轉化為Python物件
b = json.loads(a)
# 列印
print(b, type(b))
# 輸出:[{'name': '小明', 'age': 10}] <class 'list'>
2.dumps()
import json
c = [{'name': '小明', 'age': 10}]
# 將Python物件轉化為JSON字串
d = json.dumps(c, ensure_ascii=False) # ensure_ascii:ascii編碼 默認為true (中文亂碼)
print(d, type(d))
# 輸出:[{'name': '小明', 'age': 10}] <class 'str'>
3.dump()
import json
filename = 'test.json'
data = https://www.cnblogs.com/jhlp/archive/2022/11/03/[{'name': '小明', 'age': 10}]
# 把data寫入test.json檔案
with open(filename, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
4.load()
import json
filename = 'test.json'
# 讀取test.json檔案
with open(filename, 'r', encoding='utf-8') as f:
res = json.load(f)
print(res)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/526810.html
標籤:其他
上一篇:Python定義變數的方法
