cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Json conversion to new object

skhatri
New Contributor

Hi All,

Good morning,

I have a requirement for converting json into xml with attributes.

So, I understood in order to make the XML with attributes from json, I have to have below structure of json to be feed to xml formatter for final conversion.

Required JSON format,
[
โ€œh1โ€: {
โ€œh2โ€:{
โ€œfโ€:[
{โ€œ@nameโ€:โ€œField1โ€,โ€œ$โ€:โ€œ10/3930โ€},
{โ€œ@nameโ€:โ€œField2โ€,โ€œ$โ€:โ€œtrueโ€}
]
}
}

]

My Original json is like this
[
{
โ€œField1โ€:โ€œ10/3930โ€
โ€œField2โ€:โ€œtrueโ€
}
]

How to convert original json to required json structure for XML formatter.

Any help will be much appreicated.

Regards,
San

3 REPLIES 3

del
Contributor III

@skhatri,

Maybe the following expression will provide some assistance to get you close.

{"h1": { "h2": {f: $.entries().map(x => {"@name": x[0],"$": x[1]}) }}}

This expression combines the Object entries() and the Array map() functions together to build out the transformation and embeds the result into a hard-coded wrapper object for the complete body.

The attached Pipeline shows the expression in practice:
Community.17106.slp (4.7 KB)

I hope this helps

skhatri
New Contributor

Thanks Del.

It works like a charm, but I had another issue with given expression.

Usually, when we have blank value in xml, the closing field name should be removed. It doesn;t work with above expression.

For example, when Field2 is blank, it should completely remove the $ value. I tried filter function on values ($.filter((val, key) => (val != โ€˜โ€™))), but it was not working as it works on entire column($) after conversion as per our expression.

Desired output, when field2 is blank
[
โ€œh1โ€: {
โ€œh2โ€:{
โ€œfโ€:[
{โ€œ@nameโ€:โ€œField1โ€,โ€œ$โ€:โ€œ10/3930โ€},
{โ€œ@nameโ€:โ€œField2โ€}
]
}
}

]

Regards,
San

del
Contributor III

I think you can add your filter expression within the complete expression where the new object is being created:

{"h1": { "h2": {f: $.entries().map(x => {"@name": x[0],"$": x[1]}.filter((val, key) => (val != ''))) }}}