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

时间:2019-03-10 15:36:33

标签: python json file

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

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文件列表中的最后几行,但未将其添加到其中

1 个答案:

答案 0 :(得分:1)

@ 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可能没有达到您的期望。

相关问题