Peque
Peque

Reputation: 14851

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

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:

Upvotes: 14

Views: 7081

Answers (1)

blhsing
blhsing

Reputation: 107134

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.

Upvotes: 16

Related Questions