将嵌套的字典转换为每行都有主键的json。

问题描述 投票:0回答:1

我有一个嵌套的字典,我试图使用json.dumps()将其转换为JSON文件。使用下面的代码。

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)        

我得到了这个。

{
    "Galicia": {
        "ACoruña": 1,
        "Pontevedra": 2,
        "Lugo": 3,
        "Ourense": 4
    },
    "Asturias": {
        "Oviedo": 5
    },
    "Castilla": {
        "Leon": 6,
        "Burgos": 7,
        "Avila": 8
    }
}

但我想把我的JSON文件中的每个主键都放在新的行中,以使其更容易阅读。我希望它看起来像这样。


{
"Galicia": { "ACoruña": 1 , "Pontevedra": 2, "Lugo": 3, "Ourense": 4},
"Asturias": { "Oviedo": 5},
"Castilla": { "Leon": 6, "Burgos": 7, "Avila": 8}
}

有什么想法吗?

python json dictionary
1个回答
0
投票

你可能觉得很难实现。由于JASON与JS使用的太多了,很多formatters都采用了K&R风格的输出。

你可以阅读一下,看看是否有办法用你自己的自定义格式器覆盖格式器,但这很可能会有相当大的工作量。


0
投票

试试下面这个。

    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('}')
© www.soinside.com 2019 - 2024. All rights reserved.