Python json.dumps () json.dump The difference between ()

Dumps is to convert dict to STR format, loads is to convert STR to dict format. Dump and load are similar functions, but they are combined with file operation.

Code example:

import json

dic_a = {'name': 'wang', 'age': 29}
str_b = json.dumps(dic_a)
print(type(str_b),str_b) #<class 'str'> {"name": "wang", "age": 29}


dic_c = json.loads(str_b)
print(type(dic_c),dic_c) #<class 'dict'> {'name': 'wang', 'age': 29}

Then we will see the difference between dump and dumps. See the code:

import json

dic_a = {'name': 'wang', 'age': 29}
str_b = json.dumps(dic_a)
print(type(str_b),str_b) #<class 'str'> {"name": "wang", "age": 29}

#c = json.dump(dic_a)
# TypeError: dump() missing 1 required positional argument: 'fp'

c = json.dump(dic_a)

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 operation, that is, you can convert dict into STR and then store it in a file; dumps directly gives STR, that is, you can convert dictionary into str.

See the code for an example (pay attention to some small details of file operation)

import json

dic_a = {'name': 'wang', 'age': 29}
str_b = json.dumps(dic_a)
print(type(str_b),str_b) #<class 'str'> {"name": "wang", "age": 29}

#c = json.dump(dic_a)
# TypeError: dump() missing 1 required positional argument: 'fp'

c = json.dump(dic_a,open('str_b.txt','w'))

Note: dump is rarely used in practice.  

Reproduced in: https://my.oschina.net/u/3486061/blog/3065779

Read More: