【问题标题】:How to resolve TypeError: string indices must be integers如何解决 TypeError:字符串索引必须是整数
【发布时间】:2017-11-20 15:10:31
【问题描述】:

我正在尝试访问特定的 json 数据,下面是代码。我使用python 2.7。但是它出现错误 TypeError: string indices must be integers:

http = win32com.client.Dispatch('MSXML2.XMLHTTP.6.0')
http.open('POST', 'url', False, username, password)
http.setRequestHeader("Content-type"    , "text/json"             )
http.setRequestHeader("User-Agent"      , "Your User Agent String")
http.setRequestHeader("Accept-Encoding" , "gzip, deflate"         )
http.setRequestHeader("Content-Encoding", "gzip, deflate"         )
global data
http.send(json)

global data
data = http.responseText
#data=data.split("{}{}") -try to make json data print nicely but failed.
print data['responses'][0]['status']

我的json数据如下

{
    "responses": [
        {
            "tran_id": "1234",
            "UUID": "122262d7-85f8-4e53-af98-865627cb82cb",
            "status": "success",
            "messages": [],
            "result_params": {
                "record_count": "1"
            },
            "result_table": [
                {
                    "id": "101160766",
                    "rev": "13",
                    "hierarchy_id": "F80005AF46FF0000B5EA6FE06078159E80",
                    "is_current": "1"}}

,

【问题讨论】:

  • 你的 json 不正确。

标签: python json python-2.7 nested


【解决方案1】:

JSON 写错了,最后少了一些括号。

"is_current": "1"}}

应该改为

"is_current": "1"}]}]}

>>Demo<<

【讨论】:

  • JSON 是正确的。它来自某个网​​站。我是错误复制它的人。但重点就在那里。当我尝试从嵌套的 JSON 数据中读取特定数据时出现错误
  • 但是,它工作正常。你可以参考我的Demo链接
  • 我想知道是不是因为我得到的真实 json 数据没有像上面显示的那样缩进。以上数据我直接从我从邮递员应用程序获得的 json 输出中复制。信息是一样的。只有打印数据的方式不同。你认为这是它不适合我的原因吗?
  • 我试图做漂亮的打印但也失败了。但是当我打印类型(数据)时,它表明我是 unicode 类型
【解决方案2】:

a) 您的“内容类型”标头字段不正确。它应该是 application/json。

b) 您的“内容编码”标头字段可能不正确。它表示您正在发送 deflate 和 gzip 编码的数据。

【讨论】:

  • 您对 b) 有什么建议吗?导致我不熟悉 deflate 和 gzip 编码的数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 2021-03-28
  • 2021-04-28
  • 2020-06-24
相关资源
最近更新 更多