I want to convert attributes to elements in Strong-SOAP xmlToJson

980 Views Asked by At

I'm using strong-soap node.js module to convert XML string to JSON string: xmlHandler.xmlToJson()

but XML from SOAP have in tag attributes and they are converted from strong-soap to JSON element with key $attributes like:

{"fuelStation":{
"$attributes":{"id":"62611","lastUpdate":"2017-05-17T19:01:14.745Z","provider":"mdm"},
"location": ...

How can I remove this $attributes key to have JSON string like:

{"fuelStation":{
    "id":"62611","lastUpdate":"2017-05-17T19:01:14.745Z","provider":"mdm",
    "location": ...

I can only remove the whole $attributes but this is not my goal:

const root = xmlHandler.xmlToJson(null, xmlString, null);
const jsonString = JSON.stringify(root.Body.GetFuelStationsResponse, function replacer(key, value) {
                    return key !== '$attributes' ? value: undefined;
                });

Can I convert attributes into JSON properties using strong-soap xmlToJson or with JSON.stringify replacer function?

1

There are 1 best solutions below

0
On

I fixed it with JSON.stringify:

const jsonString = JSON.stringify(root.Body.GetFuelStationsResponse, function replacer(key, value) {
                if(value !== null && typeof value === 'object' && '$attributes' in value){
                    for(const k in value.$attributes) value[k]=value.$attributes[k];
                    value.$attributes = undefined;
                }
                return value;
            });