python - 在Python中将特定的JSON结构写入.json文件

标签 python json python-3.x beautifulsoup

我有以下Python代码:

import requests
import json
from bs4 import BeautifulSoup

url = requests.get('https://www.perfectimprints.com/custom-promos/20492/Beach-Balls.html')
source = BeautifulSoup(url.text, 'html.parser')

products = source.find_all('div', class_="product_wrapper")

def get_product_details(product):
  product_name = product.find('div', class_="product_name").a.text
  sku = product.find('div', class_="product_sku").text
  product_link = product.find('div', class_="product_image_wrapper").find("a")["href"]
  src = product.find('div', class_="product_image_wrapper").find('a').find("img")["src"]
  return {
      "title": product_name,
      "link": product_link,
      "sku": sku,
      "src": src
  }

all_products = [get_product_details(product) for product in products]

with open("products.json", "w") as write_file:
  json.dump(all_products, write_file)

print("Success")

这段代码按照编写的方式完美运行。问题是我想要结构而不是

[
  {
    "title": "12\" Beach Ball",
    "link": "/promos/PI-255-751/12-Beach-Ball.html?cid=20492",
    "sku": "  \n\t\t\t\t#PI-255-751\n\t\t\t",
    "src": "https://12f598f3b6e7e912e4cd-a182d9508ed57781ad8837d0e4f7a945.ssl.cf5.rackcdn.com/thumb/751_group.jpg"
  },
]

我希望它是:

{
  "items": [
    {
      "title": "12\" Beach Ball",
      "link": "/promos/PI-255-751/12-Beach-Ball.html?cid=20492",
      "sku": "  \n\t\t\t\t#PI-255-751\n\t\t\t",
      "src": "https://12f598f3b6e7e912e4cd-a182d9508ed57781ad8837d0e4f7a945.ssl.cf5.rackcdn.com/thumb/751_group.jpg"
    },
  ]
}

这是我在 Repl.it 中工作的链接,这样您就不必自己设置:https://repl.it/repls/AttractiveDimpledTheory

旁注:如果可能的话,希望能够删除 sku 中的所有 \n\t

最佳答案

在这里,您将 all_products 列表直接转储为 JSON:

with open("products.json", "w") as write_file:
    json.dump(all_products, write_file)

您想要的 JSON 只是在对象中包含该列表。类似的东西

with open("products.json", "w") as write_file:
    json.dump({'items': all_products}, write_file)

应该做你想做的事。

一般来说,Python 数据结构与其生成的 JSON 之间存在 1:1 的关系。如果您构建正确的 Python 数据结构,您将获得正确的 JSON。在这里,我们使用 dict (映射到 JSON 对象)来包装现有的 list (映射到 JSON 数组)。

Side note: Would love to also be able to remove all of the \n and \t in the skus if possible.

假设您还想删除空格,则可以使用 str.strip() ,默认情况下会去除空格:

return {
    "title": product_name,
    "link": product_link,
    "sku": sku.strip(),  # <-- here
    "src": src
}

关于python - 在Python中将特定的JSON结构写入.json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52900086/

相关文章:

php - Python 密码学 : Cannot sign with RSA private key using PKCS1v15 padding

python - 使用元组作为 json.dump 嵌套属性的键

javascript - 无法引用 JSON 中的元素

django - 如何在 django 中正确地乘以查询集中的值

javascript - Python Bokeh CustomJS : Debugging a JavaScript callback for the Taping-Tool

python - 在不使用 top 命令的情况下以百分比显示 CPU 核心使用率

python - SQL Server 透视一列并保留其他列

python - 如何将树类对象结构序列化为JSON文件格式?

javascript - 在javascript中解析json响应数组

python - 如何检查列表是否已包含 Python 中的元素?