簡體   English   中英

將嵌套字典轉換為 json,每行都有一個主鍵

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

我有一個嵌套字典,我正在嘗試使用 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}
}

有任何想法嗎?

你可能會發現這很難實現。 由於 JASON 與 JS 一起使用較多,因此很多格式化程序采用 K&R 風格 output。

您可以閱讀並查看是否有一種方法可以用您自己的自定義格式化程序覆蓋格式化程序,但這可能是相當多的工作。

在下面試試這個:

    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