简体   繁体   English

将嵌套字典转换为 json,每行都有一个主键

[英]Convert nested dictionary to a json with a principal key in each line

I have a nested dictionary which I am trying to convert to a JSON file using json.dumps().我有一个嵌套字典,我正在尝试使用 json.dumps() 将其转换为 JSON 文件。 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.但是我想把我的 JSON 放在一个新的行上,以便于阅读。 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.由于 JASON 与 JS 一起使用较多,因此很多格式化程序采用 K&R 风格 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('}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM