python - 值作为列表发送,但作为字符串接收。(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)
解决方案
问题在于您的envialambda.invoke_lambda_envia(bytes(json_result, 'utf8'))
回报string
而list
不是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
推荐阅读
- angular - 如何在Angular ngrx 8商店中调用API之前检查状态加载和加载的值是否为假?
- python - 无法在 pygal.maps.world 模块上为世界地图生成数据集
- c++ - 在 C++ 中为动态数组创建值构造函数时面临的问题
- c# - 使用 2 个项目提取 repo 时“无法加载文件名”
- r - R 中 ARIMA 的中断时间序列 - 干预的效果
- java - SAP Hybris inStockFlag 方面只有一个选项
- javascript - 如何设置 timeUpdate JS AUDIO 的间隔
- html - Django,根据用户组显示某些超链接
- c++ - 在 C++ 中使用带有迭代器和模板的 std::sort
- c++ - 设置不同小部件、按钮等的位置并使用水平滚动条创建 lineedit