json.dump(f)
simplifies writing JSON to disk.
If you ever wondered why json.dumps
ends with a "s" it's because it's specifically for working on a string, but there is another related method: json.dump
json.dumps
is for JSON serialising an object to a string, while json.dump
(no "s") is for JSON serialising an object to a file.
The methods are very related. In fact, json.dump
is a wrapper around json.dumps
. It's a method provided out of the box by Python to simplify the task of writing JSON to a file-like object.
Python core developers are very careful about what features are included in the Python builtin modules, so it makes sense to utilise the convenience methods and not reinvent the wheel? For example, these result in the same outcome:
So why not choose the easiest to read, write, and execute (the first one)?
If our GitHub code review bot spots this issue in your pull request it gives this advice:
1 | + | with open('some/path.json', 'w') as f: | |
2 | + | f.write(json.dumps({'foo': 'bar'})) |
json.dump(f)
simplifies writing JSON to disk.
- | f.write(json.dumps({'foo': 'bar'})) |
+ | json.dump({'foo': 'bar'}, f) |