【问题标题】:Don't understand this TypeError while parsing json list解析 json 列表时不理解这个 TypeError
【发布时间】:2020-06-02 17:55:23
【问题描述】:

我有一个 json URL,我正在尝试用 Python 解析它,该 url 的输出如下所示:

"data": [
        {
            "config": {
                "add": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "append": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "http_method": null,
                "remove": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "rename": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "replace": {
                    "body": [],
                    "headers": [
                        "Host: jupyter.bbs-edsapp-p001.bbs.aphp.fr"
                    ],
                    "querystring": [],
                    "uri": null
                }
            },
            "consumer": null,

我的python脚本是:

import requests
import json

response = json.loads(requests.get("http://127.0.0.1:8001/services/6ca6c203-d3b6-46c7-94d6-cad435bbfd97/plugins").text)
for p in response['data']['config']['replace']:
    print('back: ' + headers[0])
    #print('name: ' + p['name'])
    #print(p['name'])

我收到此错误:

for p in response['data']['config']['add']:
  TypeError: list indices must be integers or slices, not str.

【问题讨论】:

  • 您问题中的代码与错误消息中显示的不匹配。
  • 首先,您必须修改您的问题以将代码与错误消息匹配。其次,如果您在 json 数据中看到方括号,则表示数组,因此您只能使用整数索引访问它,例如 response['data'][0]['config']... etc

标签: python json


【解决方案1】:

response['data'] 是一个列表。如果您只期望一个条目,您可以使用response['data'][0]['config']['add']

不知道data中是否还有其他条目。您可能需要特别检查哪个数据条目包含config。 例如。

for entry in response['data']:
   if 'config' in entry:
      replace_entry = entry['config']['replace']
      # Get the host header entry
      headers = replace_entry['headers']
      host = [h for h in headers if h.startswith('Host: ')][0]

【讨论】:

  • 谢谢,但我只想得到这一行:"Host: jupyter.bbs-edsapp-p001.bbs.aphp.fr"
  • 没问题。我建议与listdict 一起玩一下,看看你可以如何使用它们以及它们的不同之处。
【解决方案2】:

由于response['data']是一个列表(不是字典),你应该写response['data'][0]['config']['add']

当然,一旦你看到它有效,你应该比盲目地输入[0] 做得更好。例如,

  • 迭代列表元素
  • 做一些检查(response['data'] 是一个列表,它是否只包含一个元素?)

【讨论】:

    【解决方案3】:

    调试你的代码?

    In [1]: type(response)
    Out[1]: dict
    
    In [2]: response.get('data')
    Out[2]: 
    
    In [3]: response.get('data').get('config')
    Out[3]: 
    
    In [4]: response.get('data').get('config').get('replace')
    Out[4]: 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多