【问题标题】:value sent as list, but received as string. (TypeError: string indices must be integers)值作为列表发送,但作为字符串接收。 (TypeError:字符串索引必须是整数)
【发布时间】:2020-04-22 00:19:05
【问题描述】:

晚上好, 我在 lambda 中有一个返回列表的函数,该值正确返回但作为字符串返回,并且我无法访问特定项目。达到价值的正确方法是什么,我将非常感谢您的支持。

函数 Lambda 是: ...

respuesta_servicio=[{"bool_respuesta":1,"resultado":response.text,"error":respuestaJson}]
return list(respuesta_servicio)

调用的返回值。

[{"bool_respuesta": 1, "resultado": "{\"errors\":\"error 21\",\"codigo\":21}", "error": "error red"}]

类型值为:

<class str>

当我从另一个 .py 文件调用该函数时,我会验证它是否以字符串形式出现。产生错误。

respuestaServ=[]
respuestaServ= envialambda.invoke_lambda_envia(bytes(json_result, 'utf8'))

os.system("echo Respuesta-python : '{}'".format( str(respuestaServ) ))

值为:

 [{"bool_respuesta": 1, "resultado": "{\"errors\":\"error 21\",\"codigo\":21}", "error": "error red"}]

os.system("echo Guia typo-python : '{}'".format( type(respuestaServ) ))

值为:

<class str>

当我想访问特定项目时,会生成错误。 accder的正确形式是什么。

os.system("echo *******************: '{}'".format( respuestaServ[0]['bool_respuesta'] ))

错误:

TypeError: string indices must be integers

lambda 代码是: 导入json 导入请求

def lambda_handler(event, context):

respuesta_servicio=[] respuesta_servicio=[{"bool_respuesta":1,"resultado":response.text,"error":respuestaJson}]

返回列表(respuesta_servicio)

【问题讨论】:

  • 您需要提供可以从头到尾执行的代码;各个部分看起来都很好(我认为),但很明显在这两者之间发生了一些我们没有看到的事情。例如,您显示的返回值肯定看起来像一个列表;你如何确定它是一个字符串?
  • 您好,感谢您的回答。我显示了变量的类型。 os.system("echo Guide typo-python: '{}'".format (type (serviceResponse)))
  • 请添加 lambda 函数
  • import json 导入请求 def lambda_handler(event, context): respuesta_servicio=[] respuesta_servicio=[{"bool_respuesta":1,"resultado":response.text,"error":respuestaJson}] 返回列表(respuesta_servicio)
  • 你好 lambda 代码,它很小,我手动返回列表,在初始请求中复制它。

标签: python


【解决方案1】:

问题在于您的envialambda.invoke_lambda_envia(bytes(json_result, 'utf8')) 返回string 而不是listdicts

一种方法可能是这样;就在之后:

respuestaServ=[]
respuestaServ= envialambda.invoke_lambda_envia(bytes(json_result, 'utf8'))

你可以使用literal_eval:

import ast
respuestaServ=ast.literal_eval(respuestaServ)

这会将字符串转换为列表:

print(respuestaServ[0]['bool_respuesta'])

输出:1

警告(per docs) 由于 Python 的 AST 编译器的堆栈深度限制,使用足够大/复杂的字符串可能会使 Python 解释器崩溃。

编辑:

import json
aa = '[{"bool_respuesta": 1, "resultado": "ganado", "error": "errores"}]'
print(json.loads(aa)[0]['bool_respuesta']) # int 1

第三种方法,如果你知道你想要的值在列表中的第一个“:”之后和第一个“,”之前:

aa = '[{"bool_respuesta": 1, "resultado": "ganado", "error": "errores"}]'
cc = [c.split(", ") for c in aa.split(":")]

print(cc[1][0]) # output string 1
print(int(cc[1][0])) # output int 1

【讨论】:

  • 谢谢,导入 ast 已解决。您是否建议我以这种方式处理它,或者我接收字符串并将其转换为 json 并将其作为 json 工作??我有疑问。
  • 不客气!如果 dict 有可能太大,我会使用 json 格式(添加到答案,编辑后检查)或第三选择。
猜你喜欢
  • 1970-01-01
  • 2016-07-19
  • 2019-11-26
  • 1970-01-01
  • 2021-03-28
  • 2021-04-28
  • 2020-06-24
  • 2016-03-26
相关资源
最近更新 更多