如何从 json 文件中删除 \n

How to remove \n from a json file

当我尝试使用终端将抓取的数据保存在 json 文件中时,品牌和品牌名称后有一个 \n ({"Brand": "\n Libra\n ", "价格”:“24.95 美元”},)。 如何解决这个问题。

import scrapy


class GlassSpider(scrapy.Spider):
    name = 'glass'
    allowed_domains = ['www.glassesshop.com']
    start_urls = ['https://www.glassesshop.com/bestsellers/']

    def parse(self, response):
        for item in response.xpath("//div[@class='col-12 pb-5 mb-lg-3 col-lg-4 product-list-row text-center product-list-item']"):
            yield {
                'Brand': item.xpath(".//div[@class='p-title']/a/text()").get(),
                'Price': item.xpath(".//div[@class='product-title p-tab p-tab-13145']/span/text()").get()
            }

可以使用strreplace方法:

...
    yield {
        'Brand': item.xpath(".//div[@class='p-title']/a/text()").get("").replace("\n",""),
        'Price': item.xpath(".//div[@class='product-title p-tab p-tab-13145']/span/text()").get("").replace("\n","")
        }