[SOLVED] Adding quotation makes to JSON String which contains some XML values

Issue

I’m trying to format a JSON input string in Javascript so that I can use it as a map.

{accountNumber:E22E6178D16777E1E053020011AC64B0,paymentMethodObject:<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>,preview:true}

To do this I need to put quotation marks around each key and value. Like here:

{
    "accountNumber": "12345",
    "paymentMethodObject": "<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>",
    "preview": "true"
}

The problem is when I try to do it, quotes get added to the XML values also because they also contain a colon.

Solution

Maybe you need to use method replace with pattern Regex that match key:value replace it with surrounded by quotes pair!

let strJSON = '{accountNumber:E22E6178D16777E1E053020011AC64B0,paymentMethodObject:<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>,preview:true}';
let objJSON = strJSON.replace(/(\w+):([\/<>:\w+]+)/g,'"$1":"$2"');
console.log(objJSON)

Answered By – TAHER El Mehdi

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.