简体   繁体   English

如何在lambda python函数中将json数组转换为json对象

[英]How to convert json array to json object in lambda python function

How to convert json array to json object in lambda python function, Below is my lambda code: 如何在lambda python函数中将json数组转换为json对象,以下是我的lambda代码:

import sys
import logging
import pymysql
import json
rds_host=".com"
name="name"
password="pass"
db_name="DB"
port = 3306
def save_events(event):
result = []
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, 
connect_timeout=30)
with conn.cursor() as cur:
  cur.execute("select * from bodyPart")
for row in cur:
  result.append(list(row))
print ("Data from RDS...")
print (result)
cur.close()
bodyparts = json.dumps(result)

def lambda_handler(event, context):
  save_events(event)
  return bodyparts

Below is the output Response: 以下是输出响应:

[[1, \"Chest\", \"link"], [2, \"Shoulder\", 
null], [3, \"Arms\", null]]

How to get a response like 如何获得像这样的回应

 {id='1',
 name='chest',
 link='......', ....}

At the moment your function save_events is not mentioning the event passed in. But the immediate problem you asked about is solved with code like this: 目前,您的功能save_events并未提及传入的事件。但是,您所要解决的紧迫问题已通过以下代码解决:

result = []

conn = pymysql.connect(rds_host,
        user=name,
        passwd=password,
        db=db_name,
        connect_timeout=30)

cursor = conn.cursor()
cursor.execute("SELECT * FROM bodyPart")

data = cursor.fetchall()
#data = [[1, "Chest", "link"], [2, "Shoulder", None], [3, "Arms", None]]

element = {}
for row in data:
    element["ident"], element["name"], element["link"] = row
    result.append(element)

print("Data from RDS...")
print json.dumps(result)
conn.close()

As mentioned in a comment, your rows are dicts not lists. 如评论中所述,您的行是字典而不是列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM