json.dump()和json.dmups()的區別

在python中支持json合適的數據是經過json模塊實現的。html

在序列化json數據的時候遇到兩個形狀很像的函數,dump()和dumps()。主要說說他們的區別python

先看看官方文檔的說明:https://docs.python.org/3.6/library/json.html#json.dump, 咱們摘出兩段來看看json

19.2.1. Basic Usage

json. dump (objfp*skipkeys=Falseensure_ascii=Truecheck_circular=Trueallow_nan=Truecls=Noneindent=Noneseparators=Nonedefault=Nonesort_keys=False**kw)

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table.函數

If skipkeys is true (default: False), then dict keys that are not of a basic type (strintfloatboolNone) will be skipped instead of raising a TypeError.ui

The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.this

.spa

.code

後面就不用看了,咱們從這能看出來,dump()是把一個對象序列化爲一個json格式的流,並把這個流給到了fp,fp也是有要求的:一個file_like對象,而且支持write()方法。orm

經過這個解釋咱們大概能想明白,無非是一個文件或者IO流對象 如 BytesIo 或 StringIo對象,咱們用三種對象都來試一下:htm

 1 json.dump({'name':'fanyuchen'}, fp=open('C:\\Users\\fyc\\Desktop\\json1.txt', 'w'))         
 2 with open('C:\\Users\\fyc\\Desktop\\json1.txt', 'r') as f:
 3     print(f.read())
 4 
 5 strIo = StringIO()
 6 json.dump({'name':'fanyuchen'}, strIo)
 7 print(strIo.getvalue())
 8 
 9 bytIo = BytesIO()
10 json.dump({'name':'fanyuchen'}, bytIo)
11 print(bytIo.read())

 

運行結果:文件和StringIo對象均可以,可是ByteIo對象報錯,緣由也是明顯的,既然要用到參數bytIo的write()方法,就要按照人家的路子來,然而BytesIo的write()方法須要接受一個 bytes_likes對象,json顯然不像 bytes_likes

Traceback (most recent call last):
File "C:/Users/fyc/liaoxuefeng/base.py", line 520, in <module>
json.dump({'name':'fanyuchen'}, bytIo)
File "C:\Python36\lib\json\__init__.py", line 180, in dump
fp.write(chunk)
TypeError: a bytes-like object is required, not 'str'

因此總結一下:dump()把一個對象按json格式序列化,能夠寫入文件,也能夠寫入StringIo類型

 

再來看json.dumps()的用法,依然是先看文檔

json.dumps(obj*skipkeys=Falseensure_ascii=Truecheck_circular=Trueallow_nan=Truecls=Noneindent=Noneseparators=Nonedefault=Nonesort_keys=False**kw)

Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump().

dumps()比較簡單,說的很明確, 把一個對象按照json格式序列化爲一個字符串。因此用起來也簡單:

1 d = dict({'name':'fanyuchen'})
2 print(json.dumps(d))
相關文章
相關標籤/搜索