Use json.dump to write JSON to file

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:

code-review-doctorbotsuggested changes just now
catalogue.py
1
+
with open('some/path.json', 'w') as f:
2
+
    f.write(json.dumps({'foo': 'bar'}))
Suggested changes
-
    f.write(json.dumps({'foo': 'bar'}))
+
    json.dump({'foo': 'bar'}, f)
Commit suggestion

json.dump(f) simplifies writing JSON to disk.

Read more
Update catalogue.py
We're your Python code review copilot. Get code improvements right in your pull request with our GitHub code review bot.

Configuring this check

Code Review Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code use-json-dump in your pyproject.toml file.

Read more about configuring Code Review Doctor.