標準庫系列 json

2022-09-09 06:18:13 字數 1610 閱讀 2379

目錄

,

]}

訪問方式:employees[0].lastname

使用json字串生成python物件(load)

由python物件格式化生成json字串(dump)

python

json

python

dict

object

dict

list,tuple

array

list

strstring

strint, float, int -& float-devived enums

number

int, float

true, false, none

true, false, null

true, false, none

注:

list轉array

np.array(a)
array 轉list

a.tolist()
方法

功能json.dump(obj,fp)

將python資料型別轉換並儲存到json格式的檔案內

json.dumps(obj)

將python資料型別轉換為json格式的字串

json.load(fp)

從json合適的檔案中讀取資料並轉換為python的型別

json.loads(s)

將json格式的字元轉換為python的型別

#規範的檔案讀寫方式:

try:

f = open("data\init.json","r")

print(f.read())

finally:

if f:

f.close()

#簡化版

with open("data\init.json","w") as f:

print(f.read())

'''dump'''

import json

#person是, 列印出來是單引號!!!true

person =

#jsonstr是, 列印出來是雙引號!!!true

jsonstr = json.dumps(person)

jsonstr = json.dumps(person, indent=4,sort_key=true)

#indent能夠改善縮排形式!

#sort_key能夠對key進行排序

with open('data.json','w') as f:

json.dump(person, open())

'''load'''

s = ''

pythonojb = json.loads(s)

'''load from files'''

pythonojb = json.load(open('emplyees.json','r'))

Python常用標準庫 json

json是一種輕量級資料交換格式,一般api返回的資料大多是json xml,如果返回json的話,將獲取的資料轉換成字典,方面在程式中處理。json庫經常用的有兩種方法dumps和loads 將字典轉換為json字串 dict type dict json str json.dumps dict ...

標準庫之JSON物件

json格式 每個json物件就是乙個值,可能是乙個陣列或物件,也可能是乙個原始型別的值,只能是乙個值,不能是兩個或更多的值.json 對值的型別和格式有嚴格的規定 復合型別的值只能是陣列或者物件,不能是函式 正規表示式物件 日期物件.原始型別的值只有四種 字串 數值 十進位制 布林值和null,不...

go筆記 標準庫 json

json資料格式通常包含兩個操作 序列化 把物件轉換成json資料型別 和反序列化 把json資料型別轉換成物件 二者操作互逆。go語言中相關標準庫為encoding json。package main import encoding json fmt type jsonexample struct...