JSON: Difference between json.dump() and json.dumps()
In a nutshell:
-
The
json.dumps()
method can convert a Python object into a JSON string. -
The
json.dump()
method can be used for writing/dumping JSON to a file/socket.
There are also minor differences on the ensure_ascii
behavior. This difference is related to how the underlying write()
function works. It operates in chunks rather than working on the whole string:
-
json.dump()
Serializes obj as a JSON-formatted stream to fp (a .write()-supporting file-like object). If
ensure_ascii
isfalse
, some chunks written to fp may be unicode instances. -
json.dumps()
Serializes obj to a JSON formatted str. If
ensure_ascii
isfalse
, the result may contain non-ASCII characters and the return value may be a unicode instance.
The following sections provide more details.
json.dumps()
According to the Python documentation:
-
Syntax:
json.dumps(dict, indent)
-
Parameters:
- Dictionary: Name of the dictionary that should be converted to a JSON object
- Indent: Defines the number of units for indentation
Example
# Python program to convert
# Python to JSON
import json
# Data to be written
dictionary ={
"testId": "12",
"name": "LoadPage",
"Group": "Regressions"}
# Serializing json
json_object = json.dumps(dictionary, indent = 4)
print(json_object)
json.dump()
According to the Python documentation:
-
Syntax:
json.dump(dict, file_pointer)
-
Parameters:
- Dictionary: Name of the dictionary that should be converted to a JSON object
- File pointer: Pointer of the file opened in write or append mode
Example
# Python program to write JSON
# to a file
import json
# Data to be written
dictionary ={
"testName" : "page load",
"steps" : 56,
"timeout" : 8.6,
"Suit" : "Smoke Test v.2865"}
with open("sample.json", "w") as outfile:
json.dump(dictionary, outfile)