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!

1
  • That's the only configuration of the indents that the built-in JSON library allows. Commented May 13, 2020 at 14:10

1 Answer 1

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(']')
Sign up to request clarification or add additional context in comments.

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.