0

My script is running fine. The only issue is writing to my Json file. It dumps all the dictionary in 1 line(the first line)

This is what I try:

data = [{'name' : 'Jan', 'age' : '30'}, {'name' : 'Peter', 'age' : '45'}, {'name' : 'Kees', 'age' : '50'}]`
`with open("data_file.json", "w") as write_file:
    for d in data:
        json.dump(data, write_file)

I expect the output:

1 [
2 {"name": "Jan", "age": "30"}, 
3 {"name": "Peter", "age": "45"}, 
4 {"name": "Kees", "age": "50"}
5 ]

But I actually get:

1 [{"name": "Jan", "age": "30"}, {"name": "Peter", "age": "45"}, {"name": "Kees", "age": "50"}]
2
3
4
5

I wanna understand way's how to do what I expect.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Rayly Esta
  • 33
  • 8
  • Use `json.dump(data, write_file, indent=2)`. There is no need to loop. Note your loop simply dumped `data` multiple times, re-writing the file wiht the exact same json each time – juanpa.arrivillaga Apr 07 '19 at 18:26
  • If you had done `json.dump(d, write_file)` in a loop, it would have simply given you `{"name": "Kees", "age": "50"}`. – juanpa.arrivillaga Apr 07 '19 at 18:28

2 Answers2

2

You can add indentation in you json by using :

json.dump(data, write_file, indent=1)

This will make your json more readable

The output will be :

[
 {
  "name": "Jan",
  "age": "30"
 },
 {
  "name": "Peter",
  "age": "45"
 },
 {
  "name": "Kees",
  "age": "50"
 }
]

this is the closest way I could think of

Eyal.D
  • 550
  • 3
  • 18
-1

You can pretty print the list using the pprint library.

from pprint import pprint
d = [{'name' : 'Jan', 'age' : '30'}, {'name' : 'Peter', 'age' : '45'}, {'name' : 'Kees', 'age' : '50'}]
pprint(d)
#Output:
[{'age': '30', 'name': 'Jan'},
 {'age': '45', 'name': 'Peter'},
 {'age': '50', 'name': 'Kees'}]
amanb
  • 5,276
  • 3
  • 19
  • 38