How to get python data out of a string
Question:
I am setting up a lambda function to put data into a db. I am using API gateway to control the endpoint.
The request I am making sends the data as a string:
fetch(
url,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name: "hello", contact: "Tim", phone: "555" }),
}
);
My lambda function keeps erroring out because it doesn’t know how to handle the string.
My function is:
import re
import psycopg2
import os
import json
def lambda_handler(event, context):
password = os.environ['DB_SECRET']
host = os.environ['HOST']
connection = psycopg2.connect(user="postgres", password=password,
host=host, port="5432",
database="postgres")
cursor = connection.cursor()
postgres_insert_query = "INSERT INTO clients (name, phone, contact) VALUES ('{0}','{1}','{2}')".format(event.get('name'), event.get('phone'), event.get('contact'))
cursor.execute(postgres_insert_query)
print(cursor.rowcount)
print(event['body'])
connection.commit()
return {
'statusCode': 200,
'headers': {
"Access-Control-Allow-Origin" : "*"
},
}
Now my print statement print(event['body'])
returns '{"name":"hello","contact":"Tim","phone":"555"}'
which is the exact data I need. However for the life of me I can’t figure out how to get the data out of the string.
Answers:
import json
data = json.loads(event['body'])
print(data['name'])
I am setting up a lambda function to put data into a db. I am using API gateway to control the endpoint.
The request I am making sends the data as a string:
fetch(
url,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name: "hello", contact: "Tim", phone: "555" }),
}
);
My lambda function keeps erroring out because it doesn’t know how to handle the string.
My function is:
import re
import psycopg2
import os
import json
def lambda_handler(event, context):
password = os.environ['DB_SECRET']
host = os.environ['HOST']
connection = psycopg2.connect(user="postgres", password=password,
host=host, port="5432",
database="postgres")
cursor = connection.cursor()
postgres_insert_query = "INSERT INTO clients (name, phone, contact) VALUES ('{0}','{1}','{2}')".format(event.get('name'), event.get('phone'), event.get('contact'))
cursor.execute(postgres_insert_query)
print(cursor.rowcount)
print(event['body'])
connection.commit()
return {
'statusCode': 200,
'headers': {
"Access-Control-Allow-Origin" : "*"
},
}
Now my print statement print(event['body'])
returns '{"name":"hello","contact":"Tim","phone":"555"}'
which is the exact data I need. However for the life of me I can’t figure out how to get the data out of the string.
import json
data = json.loads(event['body'])
print(data['name'])