首页 > 解决方案 > 值作为列表发送,但作为字符串接收。(TypeError:字符串索引必须是整数)

问题描述

晚上好,我在 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(事件,上下文):

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

返回列表(respuesta_servicio)

标签: python

解决方案


问题在于您的envialambda.invoke_lambda_envia(bytes(json_result, 'utf8'))回报stringlist不是dicts.

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

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

警告(根据文档)由于 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

推荐阅读