gpt4 book ai didi

python - 将数据附加到 json 文件中的列表

转载 作者:行者123 更新时间:2023-12-01 08:13:31 27 4
gpt4 key购买 nike

我正在制作一些东西来监视网站上的新产品,所以我尝试将所有标题添加到一个 json 文件中,该文件以 {"product_titles": []} 开头,我试图弄清楚如何将包含产品标题和尺寸的字典添加到空列表中这是我的代码

import requests
import json

url = 'https://www.supremenewyork.com/mobile_stock.json'
headers = {
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1',
'Accept': 'application/json',
'Accept-Encoding': 'br, gzip, deflate',
'Accept-Language': 'en-us'
}


req = requests.get(url, headers=headers)#

page = req.json()
categories = page['products_and_categories']
Sweatshirts = categories['Sweatshirts']


product_list = []
for sweater in Sweatshirts:
product_name = sweater['name']
product_colors = []
product_sizes = []
product_stock_levels = []
#print(product_name)
raw_product_info = requests.get('https://www.supremenewyork.com/shop/' + str(sweater['id']) + '.json', headers=headers)
product_info = raw_product_info.json()
styles = product_info['styles']
for style in styles:
colors = style['name']
full_product_name = product_name + colors
file = open
product_colors.append(colors)
for size in style['sizes']:
sizes = {size['name'] : size['stock_level']}
product_sizes.append(sizes)
with open('supreme.json', 'r+') as supremef:
data = json.load(supremef)
dump = json.dump(data['product_titles'].append({full_product_name: sizes}), supremef)


最后几行我尝试将其添加到 json 文件的列表中,但它没有将其添加到其中

最佳答案

正如 @t.m.adam 在评论中指出的 - 这里有一些解释。

您期望 append 操作返回整个对象,然后 json.dump 应该保存该对象。

此示例表明这不起作用,因为 append 返回 None

>>> mydict = {"items": [1,2,3,4]}
>>> type(mydict["items"].append(5))
<class 'NoneType'>
>>> print(mydict)
{'items': [1, 2, 3, 4, 5]}
>>>

另请参阅this question有关此行为的讨论,我在 Python 文档中找不到相关条目。

您的代码可能应如下所示:

data = json.load(supremef)
data['product_titles'].append({full_product_name: sizes})
dump = json.dump(data, supremef)
<小时/>

稍微偏离主题:

您的file = open可能没有达到您的预期。

关于python - 将数据附加到 json 文件中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55089334/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com