Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get python data out of a string

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

import json

data = json.loads(event['body'])

print(data['name'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading