4

i need to print a json data using aws lambda. this is my code

'use strict';
console.log('Loading function');

exports.handler = (event, context, callback) => {

  var addon = require('./path/to/addon');
  var sampleData=addon.getSampleData(userId);
  console.log(sampleData); // it will print correct json data
  //var sampleData="{ \"data\":{ \"key1\": \"1472722877992\", \"key2\": [ 814, 809] }}";

   callback(null, sampleData);
};

i got output like this

"{ \"data\":{ \"key1\": \"1472722877992\", \"key2\": [ 814, 809] }}"

Bu i need to get output like this

"{ "data":{ "key1": "1472722877992", "key2": [ 814, 809] }}"

in this code, i created a npm library addon using c++ code. and getSampleData is a method inside c++ code. it will return a json formated string(not a json object) .in my node.js code, console log print correct json string.

But executing this lambda function returnd output with Slashes. How to solve this issue.

1 Answer 1

4

"{ "data":{ "key1": "1472722877992", "key2": [ 814, 809] }}" isn't a valid string. It's a double quoted string with non-escaped double quotes embedded in it. That isn't valid.

Have you tried using single quotes for the string, like this?

var sampleData='{ "data":{ "key1": "1472722877992", "key2": [ 814, 809] }}';

Or have you tried just returning a JSON object like this?

var sampleData={ "data":{ "key1": "1472722877992", "key2": [ 814, 809] }};


Edit based on new info in question:

Try converting the string to a JSON object like this:

callback(null, JSON.parse(sampleData));

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

3 Comments

thanks mark, but in my case, i got json formated string from a method. console.log print correct data. but result is wrong. Question updated
I was moving from AWS-EC2 to serverless and faced this, JSON.parse(sampleData) did the trick
I am facing the backlashes problem on the other end after calling a Lambda function with the AWS CLI. Using JSON.stringify(orders) works - no backslashes in the when testing with console.log(orders). orders is a JS object that looks like this: { "id": "1", "uid": "gsmith", "items": [ { "name": "HFS - Lightweight Road Running", "single_price": "105.20", "currency": "USD", "count": "2" } ], "order_total": "210.40" } , { "id": "2",... } ]

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.