cancel
Showing results for 
Search instead for 
Did you mean: 

JSON Array transformation

SriVinayaga
New Contributor II

Hi All,

I am in requirement to transform JSON Array Object to a simple JSON Object with values in the array as below. I have thought and nothing striking to my mind. Hence any help will be appreciated. Please let me know if this is first doable in Snaplogic.

Input:
[
{
“BrandData”: [
{
“Source”: “SF”,
“SourceBrand”: “COKE”,
“Brand”: “01”
},
{
“Source”: “SAP”,
“SourceBrand”: “11”,
“Brand”: “26”
},
{
“Source”: “AS400”,
“SourceBrand”: “12”,
“Brand”: “12”
}
]
}
]

Output:
{
BrandData:
{
“SF-COKE”: “01”,
“SAP-11”: “26”,
“AS400-12”: “12”,
}
}

Please note the objects withing BrandData after transformation is based on the values of “Source”+“-”+“SourceBrand” and the value is “Brand”. Each array value will have one value in the transformed output.

Please let me know how to proceed on this.

Thanks and regards,
Sri

1 ACCEPTED SOLUTION

tstack
Former Employee

You’re looking for the toObject() method on arrays. The method takes two callbacks, one to turn the array element into the key and one to turn the element into the value. I think the following will do what you want:

$BrandData.toObject(elem => elem.Source + "-" + elem.SourceBrand, elem => elem.Brand)

I’m also attaching an example pipeline with this expression.
ArrayToObject_2019_07_26.slp (3.9 KB)

View solution in original post

9 REPLIES 9

SriVinayaga
New Contributor II

Also BrandData in the output shouldnt be within quotes.

SriVinayaga
New Contributor II

Yes Tim, we will write it to a file.

The idea is to use the file as an expr library for transformation. This file is expected to be updated once a day and other pipelines will use this expr library file like a lookup. If the left value in the exprlib file matches with the input field value, it is expected to transform to the right value.

Ah, okay… In that case, it’s okay if the property name is in quotes, either way is acceptable.

As for writing out just the document and not an array of docs, try selecting the “Format each document” option in the JSONFormatter.

Hi @tstack

I have a similar requirement here. But my input to JSON formatter snap is the output from union snap and it has many segments and not one. In that case with multiple segments how can I remove square bracket and an extra curly bracket.

Thanks,
Abinaya

Would you be able to provide an example pipeline?

One thing to try might be the GroupByN snap. If you set the count to zero, it will gather all input documents into a single output document.