โ07-26-2019 06:03 AM
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
Solved! Go to Solution.
โ07-26-2019 07:13 AM
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)
โ07-26-2019 07:13 AM
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)
โ07-28-2019 11:50 PM
Didnt expect it to be so simple. Thank you very much @tstack. Appreciate your help.
โ07-30-2019 04:15 AM
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.
โ07-30-2019 09:05 AM
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?