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:
wc
shown above).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."
dumps() takes in a json object and returns a string.
json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.
In JSON object make sure that you are having a sentence where you need to print in different lines. Now in-order to print the statements in different lines we need to use '\\n' (backward slash). As we now know the technique to print in newlines, now just add '\\n' wherever you want.
A serialized JSON is just a sequence of text, not a text file, and there's no requirement for a sequence of text to end with a newline, so the json.dump
method is right to produce an output without additional white space characters outside the boundary of the JSON object itself. In many cases such as sending the JSON object over a socket (as pointed out by @deceze in the comments), a newline would be entirely unnecessary, so it's up to the caller the decide whether or not a trailing newline is appropriate for the application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With