Python JSON格式資料的提取和儲存的實現

2022-09-28 21:09:24 字數 2808 閱讀 9432

環境:python-3.6.5

json

json(j**ascript object notation) 是一種輕量級的資料交換格式,它使得人們很容易的進行閱讀和編寫。同時也方便了機器進行解析和生成。適用於進行資料互動的場景,比如**前台與後台之間的資料互動。

python中自帶了json模組,直接import json即可使用

官方文件:

json**解析**:

json簡單說就是j**ascript中的物件和陣列,所以這兩種結構就是物件和陣列兩種結構,通過這兩種結構可以表示各種複雜的結構。

物件:物件在js中表示為括起來的內容,資料結構為 的鍵值對的結構,在物件導向的語言中,key為物件的屬性,value為對應的屬性值,所以很容易理解,取值方法為 物件.key 獲取屬性值,這個屬性值的型別可以是數字、字串、陣列、物件這幾種。

陣列:陣列在js中是中括號[ ]括起來的內容,資料結構為 ["python", "j**ascript", "c++", ...],取值方式和所有語言中一樣,使用索引獲取,字段值的型別可以是 數字、字串、陣列、物件幾種。

json模組使用

json模組提供了四個功能:dumps,dump,load,loads,用於字串和python資料型別進行轉換。

json.loads()

json.loads()方法將json文字字串轉換為python物件,從json到python的型別轉化對照如下:

json

python

object

dict

array

list

string

unicode

number(int)

intwww.cppcns.com number(real)

float

true

true

false

false

null

none

示例:import json

# json文字字串

str_list = '["a","b","c","d"]'

str_dict = ''

# json.loads將文字字串轉化為json物件,在python裡就是python物件了

data_list = json.loads(str_list)

data_dict = json.loads(str_dict)

print(type(data_list))

print(type(data_dict))

print(data_list)

print(data_dict)

執行結果:

['a', 'b', 'c', 'd']

說明:json文字字串中,資料應該用雙引號括起來,不然會報錯誤,比如上面str_list和str_dict中的值都應該用雙引號,數字就不用。

json.dumps

json.dumps()方法實現python型別轉化為json字串,返回乙個str物件把乙個python物件編碼轉換成json字串。從python到json的型別轉化對照如下:

python

json

dictgzakbjazkj

object

list,tuple

array

strstring

int, float, int- & float-derived enums

gzakbjazkj number

true

true

false

false

none

null

示例:impor程式設計客棧t json

data_list = [1,2,3,4]

data_dict =

print(json.dumps(data_list))

print(json.dumps(data_dict))

執行結果:

[1, 2, 3, 4]

說明:dumps方法可以將python資料型別轉化為json文字字串,但是可以看到當有中文的時候,轉換後中文字元都變成unicode字元,要輸出中文需要設定dumps方法的引數ensure_ascii=true設定為ensure_ascii=false。如下:

print(json.dumps(d程式設計客棧ata_dict,ensure_ascii=false))

# 執行結果:

此外,如果需要將資料儲存為文字的時候,還需要指定檔案的編碼格式為utf-8,比如將上面的data_dict資料(裡面有中文字元)儲存為data.json檔案,**如下:

with open('data.json','w',encoding='utf-8') as f:

f.write(json.dumps(data_dict,ensure_ascii=false))

否則開啟儲存的檔案,會有亂碼。

如果要處理的是檔案而不是字串,可以使用 json.dump()和json.load()來編碼和解碼json資料。比如:

# 寫入資料到檔案

data_list = [,]

with open('data2.json','w',encoding='utf-8') as f:

json.dump(data_list,f,ensure_ascii=false)

# 從檔案讀取資料

with open('data2.json','r',encoding='utf-8') as f:

data = json.load(f)

print(data)

本文標題: python json格式資料的提取和儲存的實現

本文位址:

Python JSON格式資料的儲存與讀取

模組json可以將python資料結構轉儲到檔案中,並在程式再次執行時載入該檔案的資料 儲存 json.dump 函式json.dump 接受兩個實參 要儲存資料 可用於儲存資料的檔案物件 讀取 json.load import json 如果以前儲存了使用者名稱,就載入它 否則,就提示使用者輸入使...

Python json資料的解析

import json data jsonstr json.dumps data 編碼 print type data dict print type jsonstr str print jsonstr import json data jsonstr json.dumps data 編碼 tmp ...

Python JSON 資料解析

usr bin python3 import json python 字典型別轉換為 json 物件 data json str json.dumps data print python 原始資料 repr data print json 物件 json str 執行以上 輸出結果為 python ...