4

I created a new JSON document to upload data to a couchdb instance. The code works. The problem is that the data written by the Python script is displayed in a single line by text editors. Is there a way to add linebreaks? Here is the code:

newdict = {}
outputdict = {} 
docs_list = []

for number, item in enumerate(data['docs']):
    # pprint (item)
    # print item['key'][4]
    newdict["key1"] = item['key'][0]
    newdict["yek1"] = item['key'][1]
    newdict["key2"] = item['key'][2]
    newdict["yek2"] = item['key'][3]
    newdict["key3"] = item['key'][4]
    newdict["yek3"] = item['value']['lat']
    newdict["key4"] = item['value']['long']
    docs_list.append(newdict)

outputdict["docs"] = docs_list
outputdict = json.dumps(outputdict)
pprint (outputdict)

with open("filename.json",'w') as f:
    f.write(outputdict)
kurious
  • 1,024
  • 10
  • 29
  • Possible duplicate of [how to python prettyprint a json file](http://stackoverflow.com/questions/12943819/how-to-python-prettyprint-a-json-file) – midori Feb 16 '16 at 00:23

2 Answers2

4

From this answer try outputdict = json.dumps(outputdict, indent=4) with the number of spaces you want to indent.

Community
  • 1
  • 1
Phillip Martin
  • 1,910
  • 15
  • 30
0

It sounds like its a 'Carriage Return' + 'Newline' issue which will cause the file to open as one long line in a Windows text editor.

Try:

with open("filename.json",'w', newline='\r\n') as f:

or:

with open("filename.json",'w', newline='\n') as f:

or there may even be a setting in your Text Editor to correct this issue.

Colin Dickie
  • 910
  • 4
  • 9