I have a nested dictionary which I am trying to convert to a JSON file using json.dumps(). Using the following code:
import json
dictionary={'Galicia':{'ACoruña':1,'Pontevedra':2,'Lugo':3,'Ourense':4},'Asturias':{'Oviedo':5},
'Castilla':{'Leon':6,'Burgos':7,'Avila':8}}
print(dictionary)
with open ('prueba.txt','w') as outfile:
json.dump(dictionary,outfile,ensure_ascii=False,indent=4)
I get this:
{
"Galicia": {
"ACoruña": 1,
"Pontevedra": 2,
"Lugo": 3,
"Ourense": 4
},
"Asturias": {
"Oviedo": 5
},
"Castilla": {
"Leon": 6,
"Burgos": 7,
"Avila": 8
}
}
But I would like to put in my JSON in a way that each principal key is on a new line to make it easier to read. I would like it to look like this:
{
"Galicia": { "ACoruña": 1 , "Pontevedra": 2, "Lugo": 3, "Ourense": 4},
"Asturias": { "Oviedo": 5},
"Castilla": { "Leon": 6, "Burgos": 7, "Avila": 8}
}
Any ideas?
You might find that hard to achieve. Since JASON is used so much with JS, a lot of the formatters adopt K&R style output.
You could read up and see if there is a way to override the formatter with your own custom one, but that will likely be a fair amount of work.
Try this below:
dictionary = {'Galicia': {'ACoruña': 1, 'Pontevedra': 2, 'Lugo': 3, 'Ourense': 4}, 'Asturias': {'Oviedo': 5},
'Castilla': {'Leon': 6, 'Burgos': 7, 'Avila': 8}}
print(dictionary)
with open('prueba.txt', 'w', encoding='utf-8') as outfile:
outfile.write('{\n')
for key, value in dictionary.items():
outfile.write('{0}, {1}\n'.format(key, value))
outfile.write('}')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.