【问题标题】:Python, JSON TypeErrorPython,JSON 类型错误
【发布时间】:2013-07-06 05:21:08
【问题描述】:

我正在使用 Trello API,并且在 StackOverflow 上遇到了其他人的常见问题。我尝试使用提供的解决方案,但我得到一个奇怪的错误,无法弄清楚原因。

cardlist_url = "https://api.trello.com/1/boards/" + board +  "$
r = requests.get(cardlist_url)
r = r.text
j = json.loads(r)
#Check for when due
print j['due']

但是在打印 j['due'] 时,我得到:

TypeError: 列表索引必须是整数,而不是 str

这似乎与常识不一致。顺便说一句,我输入了一些整数,但它没有任何效果! (我确实保存了它!)

【问题讨论】:

  • jlist 不是 dict

标签: python json dictionary typeerror


【解决方案1】:

什么Ashwini Chaudhary said...

有效的 JSON 文件可以由列表或字典的任意组合组成。

作为 JSON 模块工作方式的示例:

import json

listText = '["This","Is","A","Valid","Json","File"]'
dictText = '{"So":["Is","This"]}'

print type(json.loads(listText))
print type(json.loads(dictText))

这仅取决于您正在阅读的 JSON 文件的结构。如果 JSON 文件的总体结构是一个列表,您可能需要考虑从根本上发生的变化。

【讨论】:

    【解决方案2】:

    先尝试将 JSON 输出转换为字典:

    j = dict(json.loads(r))
    

    你应该能够通过它的键访问字典。

    【讨论】:

      【解决方案3】:

      试试类似的东西

      for i in range(len(J)):
         print "J number " + str(i) + " = " + J[i]
      

      这应该让您了解 J 的内部

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-02
        • 2013-09-30
        • 2015-06-25
        • 2014-03-04
        • 2016-02-22
        相关资源
        最近更新 更多