Python解析json檔案

2021-10-23 14:22:57 字數 3439 閱讀 8468

日常程式設計工作中,json是介面傳遞資料的預設格式,對json檔案的解析是很常見的步驟。python的第三方庫json讓解析json檔案變得很簡單。

在編寫介面傳遞資料時,往往需要使用json對資料進行封裝。python和json資料型別的轉換,看作為編碼與解碼。

json 函式

使用 json 函式需要匯入 json 庫:import json。

函式描述

json.dumps

將 python 物件編碼成 json 字串-轉換為string (易傳輸)

json.dump

將dict型別轉換為json字串格式,寫入到檔案 (易儲存)

json.loads

針對記憶體物件將已編碼的 json 字串解碼為 python

json.load

針對檔案控制代碼,將json格式的字元轉換為dict,從檔案中讀取 (將string轉換為dict)

json格式與python格式的對應

python

json

dict

object

list, tuple

array

strstring

int, float

number

true

true

false

false

none

null

1,讀取json檔案

json檔案內容本質上字串,當我們拿到json檔案後只有轉換成字典才方便使用,方便獲取需要的字段;

import json
# json示例

]}

]}
jsonpath =

"e:/temp_files/test.json"

with

open

(jsonpath,

'r', encoding=

'utf-8'

)as f:

jsondata = json.load(f)

print

('jsondata 資料型別:'

,type

(jsondata)

)

輸出:

jsondata 資料型別:

# json檔案轉換成字典後,我們就可以向字典一樣取資料了

version = jsondata[

"version"

]print

('version:'

,version)

netypes = jsondata[

"modelinfo"][

0]["netypes"

]print

('netypes: '

,netypes)

輸出:

version: 1.0

netypes: [『itbbu』]

2 將字典轉換成json 檔案

# 將字典寫入到json檔案中

newdict =

with

open

(jsonpath,

'a', encoding=

'utf-8'

)as f:

json.dump(newdict, f, ensure_ascii=

false

)# 如果ensure_ascii 為false,則返回值可以包含非ascii值

3 將json字串轉換成字典

json_str =

''print

('這是轉換後的資料:'

,json.loads(json_str)

)# 注意是loads,有s

print

('這是轉換後的資料型別:'

,type

(json.loads(json_str)

))

這是轉換後的資料: 

這是轉換後的資料型別:

4 將字典轉換成json字串

dicts =

print

('這是將字典轉換之後的資料:'

,json.dumps(dicts,ensure_ascii=

false))

print

('這是將字典轉換之後的資料型別:'

,type

(json.dumps(dicts,ensure_ascii=

false))

)

這是將字典轉換之後的資料: 

這是將字典轉換之後的資料型別:

5 雖然字典是最常見的型別,但是其他資料型別也是可以的

import json

print

("start to working...."

) py_ob =[1

,2.0

,"string"

,true

] jsonpath =

"e:/temp_files/test2.json"

with

open

(jsonpath,

'w',encoding=

'utf-8'

)as f:

json.dump(py_ob,f,ensure_ascii=

false

)with

open

(jsonpath,

'r',encoding=

'utf-8'

)as f2:

py = json.load(f2)

print

(type

(py))#

print

(py)

# [1, 2.0, 'string', true]

json_ob = json.dumps(py_ob)

print

(type

(json_ob))#

print

(json_ob)

# [1, 2.0, "string", true]

py_ob2 = json.loads(json_ob,encoding=

'utf-8'

)print

(type

(py_ob2))#

print

(py_ob2)

# [1, 2.0, 'string', true]

輸出:

start to working…

[1, 2.0, 『string』, true]

[1, 2.0, 「string」, true]

[1, 2.0, 『string』, true]

參考:

python指令碼解析json檔案

python指令碼解析json檔案 沒寫完。但是有效果。初次嘗試,寫的比較不簡潔。比較煩的地方在於 1,中文編碼 pspecs.decode raw unicode escape 2,花括號轉義 n format n json n n n n parameters n 屬性說明.n specs n ...

JSON庫解析json檔案

cocoa 下json開源的類庫有很多,其中jsonkit庫是非常簡單易用而且效率又比較高的。解析 舉例 import jsonkit.h 假設 strjson 是網路上接收到的 json 字串,nsstring strjson bage 3,sound def.nsdictionary resul...

Python更快的解析JSON大檔案

提出問題 今天用python的 json庫解析乙個 200mb 的json檔案,發現一次decode encode都得要 10s,這個在我開來,實在太慢了,有沒有更快的庫了?先給出我的簡單測試結果 json大小 245mb 測試方法 read檔案內容,然後一次decode,一次encode 直譯器 ...