【发布时间】: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