Skip to main content
 首页 » 编程设计

Python-将json文件编写为字典列表

2025年05月04日13tintown

我正在根据从 url 中提取的信息编写一个 json 文件。如何在单独的行上打印字典的每个元素?

这是我当前的代码:

dct=[{"name": name, 
        "cuisine": cuisine, 
        "price-range": price, 
        "address": address, 
        "rating": rating, 
        "reviews": score, 
        "district": district, 
        "url": link 
        }] 
 
    with open('openrice_data.json', 'a') as file: 
        file.write(json.dumps(dct)) 

例如,它当前打印如下:

[{"cuisine": ["Japanese", "Hot Pot", "Buffet"], "rating": [3.5], "address": [22.3825, 114.1901], "url": ["https://www.openrice.com/en/hongkong/r-wagyu-more-sha-tin-japanese-hot-pot-r172321"], "reviews": [35, 17, 8], "name": "Wagyu More", "price-range": ["$101-200"], "district": ["Sha Tin"]}] 

我希望它打印成这样:

[ 
{"name": "Chan Kun Kee", 
"cuisine": ["Guang Dong", "Dai Pai Dong"], 
"price-range": "$51-100", 
"address": [22.3884, 114.1958],  
"rating": 3.5, 
"reviews": [216, 95, 38], 
"district": "Shatin", 
"url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918" 
} 
] 

请您参考如下方法:

更新 实际上,您拥有的是字典列表。当您想添加更多元素时,您需要删除字典周围的 []。

要解决您要使用 indent=0 的特定问题。也可以考虑直接使用 json.dump。

import json 
 
l=[] 
 
dct={"name": 'name', 
    "cuisine": 'cuisine', 
    "price-range": 'price', 
    "address": 'address', 
    "rating": 'rating', 
    "reviews": 'score', 
    "district": 'district', 
    "url": 'link' 
    } 
 
l.append(dct) 
 
with open('openrice_data.json', 'w') as file: 
    json.dump(l,file,indent=0) 

输出:

[ 
{ 
"name": "name", 
"cuisine": "cuisine", 
"price-range": "price", 
"address": "address", 
"rating": "rating", 
"reviews": "score", 
"district": "district", 
"url": "link" 
} 
] 

继续

要添加更多元素,您需要这样做:

# Load json to list 
with open('openrice_data.json') as f: 
    l = json.load(f) 
 
# A new dict     
dct2={"name": 'name', 
    "cuisine": 'cuisine', 
    "price-range": 'price', 
    "address": 'address', 
    "rating": 'rating', 
    "reviews": 'score', 
    "district": 'district', 
    "url": 'link' 
    } 
 
# Append new dict 
l.append(dct2) 
 
 
with open('openrice_data.json', 'w') as file: 
    json.dump(l,file,indent=0) 

输出现在包含一个包含 2 个字典的列表。

[ 
{ 
"name": "name", 
"cuisine": "cuisine", 
"price-range": "price", 
"address": "address", 
"rating": "rating", 
"reviews": "score", 
"district": "district", 
"url": "link" 
}, 
{ 
"name": "name", 
"cuisine": "cuisine", 
"price-range": "price", 
"address": "address", 
"rating": "rating", 
"reviews": "score", 
"district": "district", 
"url": "link" 
} 
]