1. 程式人生 > >python中json.load()、json.loads()、json.dump()、json.dumps()的區別

python中json.load()、json.loads()、json.dump()、json.dumps()的區別

() ont col print pri text 字符串轉換 nco sharp

json.load()從文件中讀取json字符串

json.loads()將json字符串轉換為字典類型

json.dumps()將python中的字典類型轉換為字符串類型

json.dump()將json格式字符串寫到文件中

1.json.load()

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

print(json.load(f))

{ "name": "anthony", "sex": "man" }

2.json.loads()

#定義字典類型字符串

content = ‘{"name":"anthony","sex":"man"}‘

print type(json.loads(content))

print json.load(content)

<class ‘dict‘>

{"name":"anthony","sex":"man"}

3.json.dumps()

content = {"name":"anthony","sex":"man"}

print type(json.dumps(content))

print json.dump(content)

<class ‘str‘>

‘{"name":"anthony","sex":"man"}‘

4.json.dump()

content = ‘{"name":"anthony","sex":"man"}‘

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

json.dump(content,f)

"{ \"name\": \"anthony\", \"sex\": \"man\" }"

python中json.load()、json.loads()、json.dump()、json.dumps()的區別