Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Python JSON dump misses last newline

📅 2017-Feb-22 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ json, python ⬩ 📚 Archive

Problem

The dump method from the Python json package can be used to write a suitable Python object, usually a dictionary or list, to a JSON file. However, I discovered that Unix shell programs have problems working with such a JSON file. This turned out to be because this dump method does not end the last line with a newline character! According to the POSIX definition of a line in a text file, it needs to end with a newline character. (See here).

Solution

I replaced this:

json.dump(json_data, open("foobar.json", "w"), indent=4)

with this:

with open("foobar.json", "w") as json_file:
    json.dump(json_data, json_file, indent=4)
    json_file.write("\n")  # Add newline cause Py JSON does not

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧