About json dump and dumps

First, the basic functions are explained:

dumps is to convert dict to str format, loads is to convert str to dict format.

dump and load are similar functions, but combined with file operations.

 

See the code example:

In [1]: import json
 
In [2]: a = {'name': 'wang', 'age': 29}
 
In [3]: b = json.dumps(a)
 
In [4]: print b, type(b)
{"age": 29, "name": "wang"} <type 'str'>
 
In [11]: json.loads(b)
Out[11]: {u'age': 29, u'name': u'wang'}
 
In [12]: print type(json.loads(b))
<type 'dict'>

Then look at the difference between dump and dumps, see the code:

In [1]: import json
 
In [2]: a = {'name': 'wang', 'age': 29}
 
In [3]: b = json.dumps(a)
 
In [4]: print b, type(b)
{"age": 29, "name": "wang"} <type 'str'>
 
In [5]: c = json.dump(a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-92dc0d929363> in <module>()
----> 1 c = json.dump(a)
 
TypeError: dump() takes at least 2 arguments (1 given)

Simply put, dump needs a parameter similar to a file pointer (not a real pointer, it can be called a file-like object), which can be combined with file operations, that is to say, dict can be converted into str and then stored in the file; and dumps directly give str, that is, convert the dictionary to str.

See the code for an example (note some small details of file operations):

In [1]: import json
 
In [2]: a = {'name': 'wang'}
 
In [3]: fp = file('test.txt', 'w')
 
In [4]: type(fp)
Out[4]: file
 
In [5]: json.dump(a, fp)
 
In [6]: cat test.txt
 
In [7]: fp.close()
 
In [8]: cat test.txt
{"name": "wang"}
In [9]: json.load(fp)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-0064dabedb17> in <module>()
----> 1 json.load(fp)
 
/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.pyc in load(fp, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    285
    286     """
--> 287     return loads(fp.read(),
    288         encoding=encoding, cls=cls, object_hook=object_hook,
    289         parse_float=parse_float, parse_int=parse_int,
 
ValueError: I/O operation on closed file
 
In [10]: fp = file('test.txt', 'r')
 
In [11]: json.load(fp)
Out[11]: {u'name': u'wang'}

Reprinted from http://www.cnblogs.com/xuguanghuiblog/p/8630824.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325015316&siteId=291194637