Array functions

Is there a way to delete the first entry in an array if the length of the array is more than 1.

if the JSON looks like this:

{
“content”: {
“type”: “SHOP_ITEMS”,
“uris”: [
“Groceries”,
“Cleaning Products”,
“Household Items”
]
}
}

I want the final output to be

{
“content”: {
“type”: “SHOP_ITEMS”,
“uris”: [
“Cleaning Products”,
“Household Items”
]
}
}

Hi @rajendraj,

You could try and put this expression in a Mapper Snap:
($content.uris.length > 1) ? $content.uris.filter((item1, pos1, a1)=>(pos1 != 0)) : $content.uris
and assign it to the $content.uris Target Path.
Have the Pass Through option checked.

Hope this helps.
BR,
Dimitri

1 Like

Try slice: SnapLogic Documentation

1 Like

Yes, thanks for that. It solved my usecase. However, I bumped into next problem. Now that I have an array, while trying to insert this into postgresql where column is varchar, I get the following error:

PostgreSQL - Insert - Merge[5d2c0dcc9b085f032f5b6977_4f9e9ef4-21e4-4cc1-a7f8-3698051ca592 – bb2ca011-824e-40ed-ab8d-1377b1f37dde]
com.snaplogic.snap.api.SnapDataException: class java.util.ArrayList cannot be cast to class java.sql.Array (java.util.ArrayList is in module java.base of loader 'bootstrap'; java.sql.Array is in module java.sql of loader 'platform')
Do I have to explicitly cast it and if so what would it be?

slice will work if I have static length of JSON. Wouldnt it be more work to calculate the length and then remove the first?

Hi @rajendraj,

If you’re having trouble writing the $content.uris array, posted in the original question, then you could try one of two things.

First, try and join the array elements in a string, like so $content.uris.join(“separator_of_your_choice”). Then if you’re using SnapLogic to read the data from the database, in order to transform the string data into an array, you’d try stringData.split(“separator_of_your_choice”).

Second, you could try and stringify the array, like so: JSON.stringify($content.uris). To transform the data from the DB, you’d go with JSON.parse($stringifiedJSONArray).

BR,
Dimitri

2 Likes

The doc doesn’t actually say this, but the second parameter to slice (end) is optional. If you omit it, it will return the segment from the begin index to the end of the array. So you can just say slice(1) to omit the first element.

1 Like

Thats a clean trick. Thanks for sharing it.