【问题标题】:Facing trouble to parse json response using python面对使用python解析json响应的麻烦
【发布时间】:2017-11-20 06:05:15
【问题描述】:

运行我的脚本时出现错误 - “字符串索引必须是整数”。由于我是解析 json 数据的新手,因此我无法弄清楚自己所犯的错误。这是我尝试过的代码:

import requests
r = requests.get('https://api.redmart.com/v1.5.8/catalog/search?')
res = r.json()
for item in res:
    print(item['category_tags'][0]['title'])

我已经编辑了我的代码,在其中添加了一个 url 以使状态清晰。

【问题讨论】:

  • 打印res的值;您的代码假定 res 是一个字典列表。我敢打赌不是。如果查看不能解决您的问题,请在您的问题中包含该打印语句的第一部分。
  • 更具体地说,item 是什么?字典或列表/
  • 感谢 hpaulj 先生,为您提供清晰的信息。这是字典。
  • item 是字典key,而不是字典。你需要改为res[item] ...

标签: python json web-scraping


【解决方案1】:

最后,我把它整理好了。这是工作代码:

import requests
r = requests.get('https://api.redmart.com/v1.5.8/catalog/search?')
js = r.json()
items = js['products']
for item in items:
    print(item['title'], item['sku'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 2011-03-11
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多