uuzzairr
uuzzairr

Reputation: 21

Lambda function returns the JSON object as string to the AppSync

I have a chalice application and in that chalice application, I have a lambda function. This lambda function is the data source for my AppSync application. When I make a request and return the response from the Lmabda function, the JSON object is returned as string, and not as JSON object. I have tried so many times, but nothing worked.

This is what I am returning from the lambda function:

'''
 result = {
                    'service': service,
                    'version': version,
                    'requestID': request_id,
                    'result': {
                        'creditDecisionRecommendation': credit_decision_recommendation,
                        'creditScore': bureau_score,
                        'creditLimit': limit
                    }
                }
'''

...and this is what I get as the response:

'''
{
  "data": {
    "postKaubamaja": {
      "service": "kaubamaja-custom-scoring",
      "version": "1.0",
      "result": "{\"creditDecisionRecommendation\":\"accept\",\"creditScore\":10.8,\"creditLimit\":612.1275}"
    }
  }
}
'''

The "result" object should be a JSON object itself, but gets a string. Does someone have any idea what is wrong here?

Thanks

Upvotes: 2

Views: 1025

Answers (1)

Massifox
Massifox

Reputation: 4487

If I understand your question correctly, to turn the dictionary into JSON string just use json.dumps. Given the following input:

 result = {
                    'service': 'A',
                    'version': 'B',
                    'requestID': 'C',
                    'result': {
                        'creditDecisionRecommendation': 'D',
                        'creditScore': 123,
                        'creditLimit': 4
                    }
                }

you just need this line:

import json
json.dumps(result)

and gives the JSON string representation of the dictionary result (which is a JSON object):

'{"service": "A", "version": "B", "requestID": "C", "result": {"creditDecisionRecommendation": "D", "creditScore": 123, "creditLimit": 4}}'

Note: In python, each dictionary is by nature a JSON object.

Upvotes: 1

Related Questions