[英]appending data to a list in a json file
我正在制作一些東西來監控新產品的網站,所以我試圖將所有標題添加到一個以{"product_titles": []}
開頭的 json 文件中,我試圖弄清楚我們如何添加包含的 dicts產品標題和尺寸到空列表 這是我的代碼
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 文件中的列表中的最后幾行,但沒有將其添加到其中
正如@tmadam 在評論中指出的那樣 - 這里有一些解釋。
您希望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]}
>>>
有關此行為的討論,另請參閱此問題,我在 Python 文檔中找不到相關條目。
您的代碼應該如下所示:
data = json.load(supremef)
data['product_titles'].append({full_product_name: sizes})
dump = json.dump(data, supremef)
稍微偏離主題:
您的file = open
可能不符合您的預期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.