9

When I open and write a valid json into a file with the command below, it writes newline and carriage return characters into the data.

with open('logs/output.json', 'w') as outfile:
     json.dump(json_data, outfile, indent=2, separators=(',', ': '))

output.json looks something like this:

{\r\n \"config\": {\r\n \"app\": {\r\n \"calendar\": {\r\n \"{tenant-key}calendar.reference }

How can I prevent this?

3
  • I've seen something like this before when converting a json string to json. What is the type of json_data? Commented Nov 1, 2018 at 23:12
  • 1
    How can you prevent what exactly? What would the expected output be? Commented Nov 1, 2018 at 23:22
  • 2
    Carriage returns are valid according to the JSON spec. Why do you want to disable this default and generally valid behaviour? Commented Nov 1, 2018 at 23:52

2 Answers 2

5
json.dump(json_data, outfile, separators=(',', ':'))

Indent keywords argument needed only if you want indents on your new lines. You're activating "pretty print" by doing that.

Sign up to request clarification or add additional context in comments.

Comments

2

I got something similar to work by doing something like this:

newJson = json.dump(json_data, outfile, indent=2, separators=(',', ': '))
with open('logs/output.json', 'w') as json_file:
        json_file.write(newJson)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.