Python编写json文件作为字典列表

2024-06-12 02:23:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从一个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))

例如,当前打印如下:

^{pr2}$

我想把它打印成这样:

[
{"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"
}
]

Tags: name信息jsonurladdressrangepricefile
3条回答

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

要解决您的特定问题,您需要使用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)

输出:

^{pr2}$

继续

要添加更多元素,您需要执行以下操作:

# 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个dict的列表。在

[
{
"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"
}
]

不要使用jsonpprint非常适合这份工作。在

from pprint import pprint

obj = [{"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"]}]
with open('dumpfile.json', 'w+') as f:
    pprint(obj, f)

客户化有几个参数,具体请查看单据: https://docs.python.org/3/library/pprint.html

其他人也评论过使用pprint,但我想补充一下,pprint打印字典中Python值的表示。它们并不总是与JSON对应项相同,例如:

>>> from pprint import pprint
>>> d1 = {"value": None}
>>> pprint(d1)
{'value': None}

(这里正确的JSON序列化是{"value": null}

对于这些类型的值,更好的选择是使用json.dump或{}。您可以使用indent参数使其为每个元素打印一行。请注意,这也会将每个列表元素打印到它们各自的行中(因此,您不会为每个JSON键精确地获得一行):

^{pr2}$

但您至少可以得到正确的JSON。{Plus}你也可以扩展你的行为。例如,这允许您将Python datetime对象序列化为JSON字符串。在

相关问题 更多 >