1

I have a list of dictionaries of the form:

mylist = [{'name': 'Johnny', 'surname': 'Cashew'}, {'name': 'Abraham', 'surname': 'Linfield'}] 

and I am trying to dump that to a json this way:

with open('myfile.json', 'w') as f:
    json.dump(mylist, f)

but then the entire list is on one line in the json file, making it hardly readable (my list is in reality very long). Is there a way to dump each element of my list on a new line? I have seen this post that suggests using indent in this way:

with open('myfile.json', 'w') as f:
    json.dump(mylist, f, indent=2)

but then I get each element within the dictionaries on a new line, like that:

[
  {
    'name': 'Johnny',
    'surname: 'Cashew'
  },
  {
    'name': 'Abraham',
    'surname: 'Linfield'
  }
]

whereas what I am hoping to obtain is something like that:

[
  {'name': 'Johnny', 'surname': 'Cashew'},
  {'name': 'Abraham', 'surname': 'Linfield'}
]

Would someone have a hint? Many thanks!

Notna
  • 491
  • 2
  • 8
  • 19

1 Answers1

0

This is a dirty way of doing it but it works for me

import json

my_list = [{'name': 'John', 'surname': 'Doe'}, {'name': 'Jane', 'surname': 'Doe'}]
with open('names.json','w') as f:
    f.write('[\n')
    for d in my_list:
        #dumps() instead of dump() so that we can write it like a normal str
        f.write(json.dumps(d)) 
        if d == my_list[-1]:
            f.write("\n")
            break
        f.write(",\n")

    f.write(']')
medic17
  • 415
  • 5
  • 16