我有一个列表,我想将其转换为json。但出现以下错误:
trackerror:list indices must be integers or slices, not str
和
The 'operation' tag of the JSON file is not correct or does not exist
那会是什么?
观察:
list indices must be integers or slices, not str
它在以下行中生成:url = variables["url"]
我有:
event=
[[{'operacion': 'generar','url':'xxxxxxxx', 'items': [{'unidad': 'un', codigo'001'}]
}]]
我需要(json):
event=
{
"operacion":"generar",
"url":"xxxxxxxx,"
"items":[
{
"unidad_de_medida":"un",
"codigo":"001"
}
]
}
代码:
def lambda_handler(event, context):
payload=json.dumps(event,indent=4)
variables= json.loads(payload)
url =variables["url"] --------->>>>I have an error here too.<<<<<<<-----------
headers={'content-type': "application/json",'authorization': "xxxxxxxx",'cache-`enter code here`control': "no-cache",'postman-token': "xxxxxxxx"}
response = requests.request("POST", url, data=payload, headers=headers)
网络服务响应指示它不存在。
答案 0 :(得分:0)
这应该有效:
event=[[{'operacion': 'generar','url':'xxxxxxxx', 'items': [{'unidad': 'un', 'codigo':'001'}]}]]
json.dumps(event[0][0])
# '{"operacion": "generar", "url": "xxxxxxxx", "items": [{"unidad": "un", "codigo": "001"}]}'
答案 1 :(得分:0)
PS:您的字典键codigo
的格式不正确。如果在发帖时这不仅仅是错字,则需要先解决此问题,然后再进行任何处理。但是,由于Python会引发错误,所以我猜测这只是您帖子中的格式错误?
您的event
列表太深了,毫无意义。根据所需的输出描述,可以执行以下操作:
event = [
[
{'operacion': 'generar','url':'xxxxxxxx', 'items': [
{'unidad': 'un', 'codigo': '001'}
]
}
]
]
extractedEvents = []
for e in event:
extractedEvents.append(e[0])
print(extractedEvents)
e[0]
遍历冗余列表索引,我们将对象展平了一层,就像您指示的那样