Python嵌套的jSon对象

时间:2017-02-27 18:41:03

标签: python json

我正在尝试将我的对象嵌入另一个名为“图形卡”的对象中,但我无法搞清楚它。我尝试过一些东西,但是我没有得到我正在寻找的输出。

[
  {
    "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()

1 个答案:

答案 0 :(得分:1)

你问题中的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": [ ... ]
    ]
}