[英]Python Nested jSon Objects
我正在嘗試將我的對象嵌套到另一個稱為“圖形卡”的對象中,但是我很難弄清楚它。 我已經嘗試了幾件事,但是沒有得到想要的輸出。
[
{
"Graphics Card":
{
"Brands": "Brand Name",
"Products": "Product Name",
"Shipping": "Brand Name"
}
}
]
下面是我的代碼。 任何幫助表示贊賞。 謝謝!
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import json
my_url = 'https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphics%20cards'
# opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
# html parsing
page_soup = soup(page_html, "html.parser")
# grabs each product
containers = page_soup.findAll("div", {"class":"item-container"})
items = []
for container in containers:
brand = container.div.div.a.img["title"]
title_container = container.findAll("a",{"class":"item-title"})
product_name = title_container[0].text
shipping_container = container.findAll("li", {"class":"price-ship"})
shipping = shipping_container[0].text.strip()
items.append({"Brands": brand, "Products": product_name, "Shipping": shipping })
print(json.dumps(items, sort_keys=True, indent=4))
fout = open("text.json", 'w')
json.dump(items, fout, sort_keys=True, indent=4)
fout.close()
您問題中的JSON確實沒有任何意義。
一個人會期望
{ "graphics cards": [ {object1}, {object2},... ] }
也許是這樣,但是您丟失了數據中的關聯值...所以可能不會
{ "graphics cards": { "brands": [ ... ], "products": [...], "shipping": [...] }
話雖如此,您想這樣做。
final_items = { "Graphics Cards": items }
print(json.dumps(final_items, sort_keys=True, indent=4))
而且您的代碼工作正常。
{
"Graphics Cards": [
{
"Brands": "GIGABYTE",
"Products": "GIGABYTE GeForce GTX 1060 Windforce OC GV-N1060WF2OC-6GD Video Card",
"Shipping": "Free Shipping"
},
{
"Brands": "XFX",
"Products": "XFX Radeon GTR RX 480 DirectX 12 RX-480P8DBA6 Black Edition Video Card",
"Shipping": "$4.99 Shipping"
},
建議,盡管對於“更好的” JSON數據:將每個“品牌”分組在一起。
{
"cards": [
"GIGABYTE": [
{
"Products": "GIGABYTE GeForce GTX 1060 Windforce OC GV-N1060WF2OC-6GD Video Card",
"Shipping": "Free Shipping"
},
{
"Products": "GIGABYTE GeForce GTX 1050 Ti DirectX 12 GV-N105TWF2OC-4GD Video Card",
"Shipping": "Free Shipping"
}
],
"XFX": [ ... ]
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.