20

How can I force Python to stop writing my .json file to one line? I've tried changing the write command with open('manifest.json', 'wb') as f: to with open('manifest.json', 'w') as f: but it is still writing to one line.

Code

import json

with open('manifest.json', 'r') as f:
    json_data = json.load(f)
    json_data['server-version'] = "xxxx-x.x.x"

with open('manifest.json', 'w') as f:
    f.write(json.dumps(json_data))

print('Successful.')
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
brownzilla
  • 289
  • 2
  • 3
  • 12
  • try in your python console: `help(json.dumps)` and `help(json.dump)`. – Jason Hu Aug 21 '15 at 00:42
  • 3
    try using json.dumps(json_data, indent=4) – Romaan Aug 21 '15 at 00:50
  • @Romaan, that actually works! thank you so much! – brownzilla Aug 21 '15 at 00:52
  • possible duplicate of [Pretty print JSON python](http://stackoverflow.com/questions/22792848/pretty-print-json-python) – Dawson Aug 21 '15 at 01:03
  • I looked at that question and i didn't understand it, that's why I posted my own question and for clarification. :)@Dawson – brownzilla Aug 21 '15 at 01:07
  • this is probably the wrong way to look at things: formatting JSON with whitespace is an additive operation. You are increasing the content, and adding undefined bias. It is harder to process, harder to parse, and cannot be accumulated in a file linewise for easy parallelization. You should think of formatting the JSON as a feature you might *add* for human readability that has a large usability downside; not as a default defined such that un-formatted JSON is a "restriction" to some more complex state (it is not; **unformatted json with a newline suffix is a simplification**). – Chris Aug 04 '20 at 12:57

1 Answers1

31

For pretty printing use indent parameter

print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4, separators=(',', ': ')))
Maksym Kozlenko
  • 10,273
  • 2
  • 66
  • 55