【问题标题】:Why are commas not separated when I mess up in json?当我在json中搞砸时,为什么逗号不分隔?
【发布时间】:2021-09-08 18:34:10
【问题描述】:

我正在尝试解析站点,这是我的代码,但是为什么当我导入 json 时,没有添加逗号

with open("all_categories_dict.json") as file:
  all_products = json.load(file)


specifications_list = []
specifications_dict = {}
for product_name, product_href in all_products.items(): 
  url = product_href
  response = requests.get(url)
  soup = BeautifulSoup(response.text, "lxml")

  price = soup.find("div", class_="new_price")
  price = price.text
  describe = soup.find("div", class_="additional_info").find(class_="tabs").find_all("li") 
  for specification in describe:
    specifications_list.append(["Наименование товара", product_name])
    specifications_list.append(["Ссылка", product_href])
    specifications_list.append(["Цена", price])
    specifications_list.append(specification.text.replace('\r\n\t', "").strip().split(':'))
  for i in range(0, len(specifications_list)):
    specifications_dict[specifications_list[i][0]] = specifications_list[i][-1]
  with open("specifications.json", "a") as f:
    json.dump(specifications_dict, f, indent=4, ensure_ascii=False)

这是来自 json 的截图

【问题讨论】:

标签: python json parsing


【解决方案1】:

您正在将多个 json 文件转储到同一个文件中。您可能想要生成 1 个大 json

【讨论】:

  • 我该怎么做?
  • 不要在 for 中使用 json.dump,而是创建一个 dicts 列表,然后将它们 json.dump 到循环之外。
  • 你能给点提示吗?我尝试了不同的方法,但没有任何效果
  • ``` result_list = [] for product_name, product_href in all_products.items(): .... result_list.append(specifications_dict) json.dump(result_list, f, indent=4, ensure_ascii=错误)```
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 2011-06-30
  • 2011-02-25
  • 2016-04-16
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多