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:
- 【ipfs-api】npm ERR! JSON.parse package.json must be actual JSON, not just JavaScript.
- package.json And package- clock.json The difference between
- Node.js Medium package.json The difference between devdependences and dependencies
- [jQuery] jQuery operates on JSON strings or JSON objects
- Configuration file for vscode setting.json UI interface or JSON form
- Error reading JSON file: json.decoder.JSONDecodeError : Extra data: line 6 column 2 (char 1329)
- Unable to read workspace file ‘D:\angular.json‘: Invalid JSON character: “ “ at
- User defined profile in vscode settings.json And default configuration defaultSettings.json
- JSON data format net.sf.json .JSONException: A JSONObject text must begin with ‘{‘ at character 1 of Error:(f…
- Python’s json.loads Invalid control character
- Pg_dump Error: pg_dump: No matching tables were found,pg_dump: schema with OID 1515227 does not exi
- Object is JSON, and JSON is converted to object
- Type error: the JSON object must be STR, bytes or byte array, not ‘textiowrapper’
- json.load (file) error
- Transformation of JS map and JSON
- Error resolution of unexpected token in JSON at position 0
- Object of type timestamp is not JSON serializable
- Notepad + + install JSON format plug-in
- 209151; org.json.JSONException A JSONObject text must begin with'{‘at character 1 of {
- Unexpected token o in JSON at p