node.jsjsonibm-watsonwatson-assistantibm-cloud-functions

IBM Cloud Functions printing API response in Watson Assistant / node.js / json


With IBM cloud functions I am calling two Joke APIs. The first one gives me these results:

Results:
{
  "response": {
    "body": {
      "body": [
        {
          "_id": "5f80ccd641785ba7c7d27bc0",
          "punchline": "They always egg-cercise!",
          "setup": "How do hens stay fit?",
          "type": "general"
        }
      ],
      "success": true
    },

I want to print the punchline and setup in Watson assistant so I tried this code: $webhook_result_1.response.body.body.setup and $webhook_result_1.response.body.body.punchline but both gives me an error. When I use $webhook_result_1.response.body.body I get this:

[{"_id":"5f80ccd641785ba7c7d27c07","punchline":"A JOKE MACHINE!?","setup":"What do I look like?","type":"general"}]

So I guess I am on the right way. What am I doing wrong?


ā€”
This is the response for the second joke API:
Results:
{
  "response": [
    {
      "id": 299,
      "punchline": "The meat-ball.",
      "setup": "Where do hamburgers go to dance?",
      "type": "general"
    }
  ]
}

And I tried this: $webhook_result_2.response.punchline but it is not working as well.

How can I print the punchline and setup for each API?


Solution

  • The [] indicates an array, so you need to index it. Ideally you should check an array to see that it has at least one element, and then iterate through it, but your 1st element, if it exists, will be:

    $webhook_result_1.response.body.body[0].setup
    

    Based on the comments to your question, it appears that you are placing the opening bracket in the wrong place.