python學習筆記06 json操作

2022-06-29 23:03:12 字數 1779 閱讀 8189

json就是一串字串(json只有雙引號;字典是單引號)

1.字典轉成json

1

import

json2#

json模組作用:python的資料型別和json相互轉換的

3 d = 45

#字典轉成字串(json)

6 json_str = json.dumps(d, indent=4, ensure_ascii=false) #

indent縮排字元,為了看著直觀;ensure_ascii顯示中文

7print

(json_str)89

#將字典轉成json寫入檔案--dumps和dump10#

dumps:先用dumps轉成json,再寫入檔案

11 json_str = json.dumps(d, indent=4, ensure_ascii=false)

12 with open('

u1.json

', '

w', encoding='

utf-8

') as f:

13f.write(json_str)

1415

#dump:直接用dump轉成json寫入檔案

16 with open('

u1.json

', '

w', encoding='

utf-8

') as f:

17 json.dump(d, f, indent=4, ensure_ascii=false)

2.json轉成字典

1

import

json

23 json_str = """410

"""1112#

字串(json)轉成字典

13 dic =json.loads(json_str)

14print

(dic)

1516

#讀檔案裡的json再轉成字典--loads和load17#

loads:先讀檔案,再用loads傳字串,轉字典

18 with open('

u2.txt

', encoding='

utf-8

') as f:

19 content =f.read()

20print(json.loads(content))

2122

#load:直接用load傳檔案(自動做了一次讀檔案),轉成字典

23 with open('

u2.txt

', encoding='

utf-8

') as f:

24 result = json.load(f)

25print(result)

json轉成字典報錯

1

#若json格式不合法,報錯

2 json_str = """39

"""10 dic =json.loads(json_str)

11print

(dic)

12#

報錯如下圖:

校驗json格式

Python學習筆記06

使用 json 函式需要匯入 json 庫 import json json.dumps 用於將 python 物件編碼成 json 字串 json.dumps obj,skipkeys false,ensure ascii true,check circular true,allow nan tr...

springboot學習筆記 2 搞定json引數

springboot學習筆記 2 搞定json引數 三步搞定 注 spring boot處理 json 引數的三個步驟 一 新增fastjson的依賴到pom.xml中 com.alibaba fastjson 1.2.47 二 建立controller類 三 建立配置類 四 然後啟動 驗證即可。返...

python學習筆記06(讀寫檔案)

created on mon feb 12 00 18 30 2018 author myself f open data.txt 開啟檔案 data f.read 檔案內容寫入字串data print data 輸出字串 f.close 關閉檔案,釋放資源runfile f python list...