Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `json.dump()` not ending the line with `\n`?

Tags:

python

json

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.
like image 469
Peque Avatar asked Feb 15 '19 19:02

Peque


People also ask

Does JSON end with a newline?

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."

Does JSON dumps return a string?

dumps() takes in a json object and returns a string.

What is the difference between JSON dump and JSON dumps?

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.

How do I create a new line in JSON?

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.


1 Answers

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.

like image 76
blhsing Avatar answered Oct 21 '22 19:10

blhsing