Python, List to Json



下午好。

我试图将列表中的所有项目转换为Json并保存到文件中,使用python我已经读过,我需要将每个项目作为item.__dict__,这给了我python shell上所需的输出,当将其保存到文件并验证Json之后,它是不正确的。

所以我想找出的是将列表中的项转换为json的最佳方法是什么

import json
import requests
from bs4 import BeautifulSoup
list1 = []

class BountyItem:
def __init__(self, heading, price, tickets):
self.heading = heading
self.price = price
self.tickets = tickets

url = 'https://www.bountycompetitions.co.uk/live-competitions/'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
result = soup.find_all(class_='product')
for item in result:
item_heading = item.find('a', attrs={'class': 'product-item-heading'})
item_price = item.find('span', attrs={'class': 'woocommerce-Price-amount amount'})
item_tickets = item.find('span', attrs={'class': 'status'})
b_item = BountyItem(item_heading.text, item_price.text[1:], item_tickets.text)
list1.append(BountyItem(b_item.heading, b_item.price, b_item.tickets))
for item in list1:
with open("/home/pr0xibus/Documents/test.txt", 'a') as file:
json.dump(item.__dict__, file)

json的输出看起来像

{
"heading": "Highland Park u2013 Valhalla Collection u2013 Odin 16 year old Whisky",
"price": "1.20",
"tickets": "249 Left"
} {
"heading": "Tom Ford Rose Prick Collection",
"price": "0.99",
"tickets": "189 Left"
} {
"heading": "On The Go Giga Gaming Bundle",
"price": "2.00",
"tickets": "242 Left"
} {
"heading": "Brand New 2020 KTM 450 SX-F",
"price": "2.99",
"tickets": "378 Left"
}

您可以像这样转储列表,而不是附加单个对象

with open("/home/pr0xibus/Documents/test.txt", 'w') as file:
json.dump([item.__dict__ for item in list1] , file)

相关内容

  • 没有找到相关文章

最新更新