0

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='......', ....}
4
  • 1
    Apply the data from the row to a dict instead of just doing list(row). Commented Feb 22, 2019 at 2:47
  • 1
    Use with conn.cursor(pymysql.cursors.DictCursor) as cur. Then cur.fetchall() wil return a list of dicts, with the column names as keys. Commented Feb 22, 2019 at 3:21
  • @ekhumoro I used the above connector instead of a normal connector, an empty json object is getting returned Commented Feb 22, 2019 at 3:49
  • 1
    Well, you probably need to do result = cur.fetchall(), and get rid of the for-loop. Commented Feb 22, 2019 at 3:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.