【问题标题】:Unable to convert returned JSON data into Dict in Scrapy无法将返回的 JSON 数据转换为 Scrapy 中的 Dict
【发布时间】:2015-04-15 07:27:14
【问题描述】:

我正在使用scrapy 从here 获取某条数据。正如here 所建议的那样,我在脚本中使用了以下代码:

pattern = re.compile(r"qubit_product_list = (.*?);", re.M)
        script = hxs.select("//script[contains(., 'qubit_product_list')]/text()").extract()[0]
        data = pattern.search(script).group(1)

        j_data = json.loads(data)
        self.log('After calling LOAD Begins')
        self.log(j_data) #It is not printing ANYTHING!!!!
        self.log('After calling LOAD Ends')

        self.log('\n---------------------------------\n')

变量data的输出如下:

{
    "9102-DBL-sprung slat base": {
        "id": "9102",
        "name": "Imperial Bedstead",
        "url": "/p/Imperial_Bedstead.htm",
        "description": "Double - Sprung Slat Base",
        "unit_price": 429.99,
        "unit_sale_price": 429.99,
        "currency": "GBP",
        "sku_code": "BENT:1320B-Beech",
        "category": "Bed Frames",
        "stock": 100
    },
    "9102-KS-sprung slat base": {
        "id": "9102",
        "name": "Imperial Bedstead",
        "url": "/p/Imperial_Bedstead.htm",
        "description": "Kingsize - Sprung Slat Base",
        "unit_price": 439.98996,
        "unit_sale_price": 439.98996,
        "currency": "GBP",
        "sku_code": "BENT:1326B-Beech",
        "category": "Bed Frames",
        "stock": 100
    }
}

现在,我想将这个类似json 的结构转换为 python dict。我尝试关注但它返回 unicode 类型。

j_data = json.loads(data)

那么,如何在 Python 2.7 中获取 Array/Dict?具有讽刺意味的是,使用 scrapy shell 时,loads 方法返回的类型为 dict。

【问题讨论】:

  • 在 Python 2.7 下使用 json.loads 没有任何问题。
  • 这不是已经是python字典了吗?虽然是嵌套的。您的数据变量已经是 dict 类型。
  • @Siddhant 它显示为dict。在控制台上使用时,dict 类型显示相同的内容,但通过 Python 服务器运行时,它被视为字符串。
  • @Siddhant 从代码可以看出,data 是正则表达式的结果。它是一个字符串,而不是字典。它必须被解析。
  • @Volatil3 试试self.log(str(j_data))

标签: python json python-2.7 dictionary


【解决方案1】:

试试这个:

#typecasting the JSON to string for json.loads to work
data = str(data)
#returning type dict from json
j_data = json.loads(data)
#typecasting the dict to string before writing to log
self.log(str(j_data)) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-18
    • 2022-08-11
    • 1970-01-01
    • 2019-09-27
    • 2015-10-06
    • 1970-01-01
    • 2021-08-06
    • 2019-10-08
    相关资源
    最近更新 更多