mohith
mohith

Reputation: 45

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='......', ....}

Upvotes: 0

Views: 2755

Answers (1)

Alex Harvey
Alex Harvey

Reputation: 15472

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.

Upvotes: 1

Related Questions