Json.dump vs json.dumps in Python
The difference between json.dump and json.dumps is actually quite visible:
- dump() – dumps into a file or StringIO
- dumps() – dumps a string, that could be printed
Still, I am going to give a few example with these, as the dumps has a few nice built-in features:
-
- ensure_ascii = False – allowing it to print even cyrillic
- indent = 4 – making the JSON string look beautiful
- sort_keys = True – sorting the beautiful JSON string
import json
from io import StringIO
info1 = [100, 200, 300, "триста"]
print(json.dumps(info1))
info2 = {"Programming Language": "ВБА", "Max weight": 100, "In letters": "sto"}
print(json.dumps(info2))
print(json.dumps(info2, ensure_ascii=False, indent=4, sort_keys=True))

The dump (without “S”) can also ensure ascii, indent and sort the keys and this is the reason why I am not going to demonstrate it. Still, continuing the code from above, we may produce a nice file named “RealDeal.txt” with two lines in it, using the following code:
file = StringIO()
json.dump(info2, file, ensure_ascii=False)
print(file.getvalue())
file.write('\nvitoshacademy.com')
with open("RealDeal.txt", "w") as text_file:
print(f"{file.getvalue()}", file=text_file)
file.close()
That’s all folks!