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

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)

SriVinayaga
New Contributor II

Didnt expect it to be so simple. Thank you very much @tstack. Appreciate your help.

SriVinayaga
New Contributor II

Hi @tstack,

There is a catch in my requirement.

You can see there is a flower bracket at the open and end of the output instead of square bracket. Currently your solution helped to form the data, but still this issue is lingering, Any thoughts on how to transform them? I tried JSON replace, and other options etc. Did not progress further.

Iโ€™m not quite clear on what youโ€™re asking for here. What does the rest of your pipeline look like? Are you trying to write the document to a file?

Property names in JSON are quoted, so theyโ€™re necessary. Are you trying to write to a file?