Scripting inside SAP Conversational AI chatbots is a key feature, enabling developers to parse API responses or convert bits of conversations to display the way they want.

The developers in the community ask how to do all kinds of crazy things within scripting. Well, not really crazy, but developers are used to doing whatever they want in standard coding languages, and admittedly, the scripting available for chatbots can be limiting.

But I like a challenge, and I like to believe that you can accomplish anything if you are a little creative. Here’s a recent example that was given to me.

The Challenge

The developer had an API that returned a JSON array of objects, as follows:

[
   {
      "CustomerID": "123123",
      "CustomerName": "Aerosmith"
   },
   {
      "CustomerID": "123123",
      "CustomerName": "Aerosmith"
   },
   {
      "CustomerID": "999999",
      "CustomerName": "AC/DC"
   },
]

But the developer wanted to take the JSON and get rid of duplicates. Duplicates were defined as multiple objects with the same CustomerID, whether or not the Customer Name is the same.

SAP Conversational AI scripting has a unique helper function, but this only works on a simple array of strings or numbers. At first I tried to store an array of unique customer IDs, which is easy to do, but this did not help me.

I was stumped

My Solution

To be honest I don’t remember how I came across this idea, but I took it in 2 steps.

First, I took the array (which I had stored in memory under myarray), and created from it an object with a series of attributes, each attribute being the ID of a different customer. I used the following code:

{
    {{#eachJoin memory.myarray}}
       "{{this.CustomerID}}" : {{this}}
    {{/eachJoin}}
}

The secret is that you cannot have an object with 2 attributes with the same name. So when there was a duplicate (or triplicate), the new attribute would simply overwrite the previous one with the same name. Now I had something like this:

[
  { 
    "123123" : {
         "CustomerID": "123123",
         "CustomerName": "Aerosmith6"
          },
   "999999" : {
         "CustomerID": "999999",
         "CustomerName": "AC/DC"
         }
  }
]

The second and last step was simply to reformat the object in its original array form.

[
   {{#eachJoin memory.myarray2}}
      {{this}}
   {{/eachJoin}}
]

Let me know if you’ve had any challenges with scripting and how you solved them.

Sara Sampaio

Sara Sampaio

Author Since: March 10, 2022

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x