Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am not getting appropriate JSON response from Amazon Lambda

Hey helpful folks at StackOverflow! I find myself needing some of your help and expertise. I am following a tutorial on creating Amazon Alexa skills, when I test the code for the lambda function, it succeeds, however, when I use the sample utterance I designated to it, which is "get current weather" (do not mind that the utterance is not relevant to the actual endpoint, at this point I am using an endpoint from json place holders: https://jsonplaceholder.typicode.com/users because I just want a response, any type of response). I would definitely appreciate any form of help! Thanks in advance guys and gals!

Here is my code:

var https = require("https");



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

  try{

    if (event.session.new){
    // New Session
    console.log("new session!");
}
  switch (event.request.type){

    case "LaunchRequest":
    // > Launch Request
      console.log("launch request!");
      context.succeed(
        generateResponse(
          buildSpeechletResponse("Welcome!!!!!!!! Let's make this work!", true),
          {}
          )
      )
      break;

    case "IntentRequest":
    // > Intent Request
      console.log("intent request!"); // endpoint added here below
      switch(event.request.intent.name){
        case "getWeatherIntent":
          var endpoint = "https://jsonplaceholder.typicode.com/users"; // this works with this "placebo endpoint data" https://jsonplaceholder.typicode.com/posts ***** api.openweathermap.org/data/2.5/weather?zip=10005,us&APPID=08d6215ef934232110949692d5ffb8da
          var body = ""
          https.get(endpoint, (response) => {
            response.on('data', (chunk) => {body += chunk})
            response.on('end', () => {
              var data = JSON.parse(body);
              var weatherCount = data.userId; // might have something to do with this variable
              context.succeed(
                generateResponse(
                  buildSpeechletResponse("current is ${weatherCount}", true),
                  {}
                  )
                )
            })
          })
      }
      break; // endpoint added here above

    case "SessionEndedRequest":
    // > Session Ended Request
      console.log("session ended request!");
      break;

    default:
      context.fail("invalid request type!: {event.request.type}");
  }

  } catch(error) {context.fail("Exception: ${error}")}



}

// Helpers
buildSpeechletResponse = (outputText, shouldEndSession) => {
  return{
    outputSpeech:{
      type: "PlainText",
      text: outputText
    },
    shouldEndSession: shouldEndSession
  }
}

generateResponse = (speechletResponse, sessionAttributes) => { 
  return {
    version: "1.0",
    sessionAttributes: sessionAttributes,
    response: speechletResponse
  }
}

Also here is the intent schema:

{
  "intents":[
   { "intent": "getWeatherIntent"
   }
  ]
}

Here is the lambda request:

{
  "session": {
    "sessionId": "SessionId.51e05faf-df95-420f-9cfc-3736b1839482",
    "application": {
      "applicationId": "amzn1.ask.skill.482872e5-20a2-4230-bce4-a06b212443e5"
    },
    "attributes": {},
    "user": {
      "userId": "amzn1.ask.account.AFOFPAF44SZKQRQDFH3FW7PZCVEZPXLLPPWT7CO76Z62I2DVI5EFTYSFD3YMEA56R4ACYUSPTPVFGCA2BCFJCNBVLBNWAWSIOCXHCDTW5UM5WNIRE6K35XZ67CM3W2DN3NLIPRVEFWBZ3D6ASD37EYJWBQQFOK4FXB5NMGQCLJVGBJKUJMCZXVEHXU74KLSDXOV5MIF3UZPFLRA"
    },
    "new": true
  },
  "request": {
    "type": "IntentRequest",
    "requestId": "EdwRequestId.4b18c102-47ea-4855-a5da-6407379c0384",
    "locale": "en-US",
    "timestamp": "2017-02-28T02:13:25Z",
    "intent": {
      "name": "getWeatherIntent",
      "slots": {}
    }
  },
  "version": "1.0"
}

Here is the lambda response:

{
  "version": "1.0",
  "response": {
    "outputSpeech": {
      "type": "PlainText",
      "text": "current is ${weatherCount}"
    },
    "shouldEndSession": true
  },
  "sessionAttributes": {}
}

Shouldn't the variable ${weatherCount} already return something parsed from JSON instead of returning again as is?

Here is the new Lambda response after changing the quotes around template literals to backticks (changing "${weatherCount}" to ${weatherCount} ) so we might be onto something!:

{
  "version": "1.0",
  "response": {
    "outputSpeech": {
      "type": "PlainText",
      "text": "current is [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]"
    },
    "shouldEndSession": true
  },
  "sessionAttributes": {}
}

It's working now! The key was to change the quotes surrounding the template literals into backticks. Here are is the new lambda request and the new lambda response.

Lamdba Request:

{
  "session": {
    "sessionId": "SessionId.9f8cc454-110f-4610-a7fe-cd0918fd804f",
    "application": {
      "applicationId": "amzn1.ask.skill.482872e5-20a2-4230-bce4-a06b212443e5"
    },
    "attributes": {},
    "user": {
      "userId": "amzn1.ask.account.AFOFPAF44SZKQRQDFH3FW7PZCVEZPXLLPPWT7CO76Z62I2DVI5EFTYSFD3YMEA56R4ACYUSPTPVFGCA2BCFJCNBVLBNWAWSIOCXHCDTW5UM5WNIRE6K35XZ67CM3W2DN3NLIPRVEFWBZ3D6ASD37EYJWBQQFOK4FXB5NMGQCLJVGBJKUJMCZXVEHXU74KLSDXOV5MIF3UZPFLRA"
    },
    "new": true
  },
  "request": {
    "type": "IntentRequest",
    "requestId": "EdwRequestId.229831d9-3bd1-4173-a1c4-7664994a1a77",
    "locale": "en-US",
    "timestamp": "2017-02-28T02:39:30Z",
    "intent": {
      "name": "getWeatherIntent",
      "slots": {}
    }
  },
  "version": "1.0"
}

new Lambda Response:

{
  "version": "1.0",
  "response": {
    "outputSpeech": {
      "type": "PlainText",
      "text": "current is 1"
    },
    "shouldEndSession": true
  },
  "sessionAttributes": {}
}
like image 525
Marcode777 Avatar asked Jun 20 '26 18:06

Marcode777


1 Answers

This seems to me like an issue with your template literals. Template literals need to be wrapped by backticks instead of single or double quotes. Replace the quotes with backticks for all of your strings that use template literals.

So for example this:

"current is ${weatherCount}"

becomes:

`current is ${weatherCount}`

Additional troubleshooting tips:

  • Make sure you're using the latest version of node available to AWS Lambda; at the time of this writing, that is v4.3.2. Older versions of node don't support template literals.

  • Failing either of those steps, simply replace the template literals with variables to rule that out as your issue.

  • console.log output is written to cloudwatch in AWS Lambda -- you can use this to debug each invokation of your lambda function. More info here: http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-logging.html

like image 57
Anthony Neace Avatar answered Jun 23 '26 11:06

Anthony Neace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!