Adding a Line Break to a User Input Variable Python Then Storing it in a JSON File

Question:

So I have this program and in the program is a Tkinter entry box and when the user clicks the submit button it stores the input to a JSON file. How can I add a line break after the string has been written in JSON file?

I’ve tried using the newline="rn" in the

with open(udf, "a", newline="rn") as file_object:
    json.dump(usern, file_object)

By the way, the varible usern is what the user typed in to the entry box.

And the new line feature in it:

with open(udf, "a") as file_object:
    json.dump(usern + "n", file_object)

But none of it worked

Asked By: AngusAU293

||

Answers:

The json module does not support adding newlines to the file when dumping data.

You can use file_object.write("n") to add it to the file after dumping:

with open(udf, "a") as file_object:
    json.dump(usern, file_object)
    file_object.write("n")

Or convert it to a string with json.dumps() and make a single write operation:

with open(udf, "a") as file_object:
    json_string = json.dumps(usern) + "n"
    file_object.write(json_string)
Answered By: Jason Barnwell
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.