When serializing with Python's json
module, the dump
function is not adding a newline character at the end of the line:
import json
data = {'foo': 1}
json.dump(data, open('out.json', 'w'))
We can check that using wc
:
$ wc -l out.json
0 out.json
Why is it doing that? Considering that:
- The serialized JSON is a text file and text files should end with a newline
- The POSIX standard defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
- Python's documentation notes that "Unlike pickle and marshal, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file.
- Many tools expect that newline (like
wc
shown above). - Many editors will add it automatically if you edit the JSON file by hand.