0

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?

Warkus
  • 64
  • 8
  • I guess it has something to do with this bracket `[` after response body body and for the second API after response - but I don't get how to address that – Warkus Jan 19 '21 at 14:46
  • Because other APIs with a different responses structure, without `[`, I can print easily.. – Warkus Jan 19 '21 at 14:51
  • [] is a JSON array, e.g., if there could be multiple entries. You could use body[0].punchline – data_henrik Jan 19 '21 at 15:01
  • I tried a few combinations to make sure but it isn't working with body[0] as well :/ @data_henrik – Warkus Jan 19 '21 at 15:12
  • $webhook_result_1.response.body.body0].punchline did not work? – data_henrik Jan 19 '21 at 15:20
  • right :( watson will print this `[{"_id":"5f80ccd641785ba7c7d27c13","punchline":"High definition.","setup":"What do you call a dictionary on drugs?","type":"general"}][0].punchline` @data_henrik – Warkus Jan 19 '21 at 15:24
  • IT way be worth trying $webhook_result_1.response.body.body[0].punchline ?> – timd Jan 20 '21 at 09:31
  • @timd you are amazing - thanks! works! – Warkus Jan 20 '21 at 11:04

1 Answers1

0

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.

chughts
  • 4,210
  • 2
  • 14
  • 27
  • Thank you for your answer. You and henrik are right. However it only worked with ` $webhook_result_1.response.body.body[0].punchline ?>` Thanks to @timd – Warkus Jan 20 '21 at 11:07