简体   繁体   中英

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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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