Skip to content Skip to sidebar Skip to footer

Javascript Regular Expression To Wrap Unquoted Json Values (not Keys) With Double Quotes

I have been trying to wrap some malformed JSON values with double quotes. The response is from a Java Servlet (its actually a hashmap) which I have no control over. I have managed

Solution 1:

Here's a way to quote all keys and values, as you want:

hashmap = hashmap.replace(/ /g, '')                  // strip all spaces
                 .replace(/([\w]+)=/g, '"$1"=')      // quote keys
                 .replace(/=([\w]+)/g, ':"$1"')      // quote values
                 .replace(/=([[{])/g, ':$1');        // = to : before arrays and objects also

This produces:

{"response":{"type":"000","products":[{"id":"1","name":"productone"},{"id":"2","name":"producttwo"}],"status":"success"}}

Now you can convert it to JavaScript object with:

obj = JSON.parse(hashmap);

However, more in line with JSON parsing would be not to quote numeric values, but rather to parse them as numbers, like this:

hashmap = hashmap.replace(/ /g, '')
                 .replace(/([\w]+)=/g, '"$1"=')
                 .replace(/=([a-zA-Z_]+)/g, ':"$1"')
                 .replace(/=([\d]+)/g, function(m, num) {return':'+parseFloat(num)})
                 .replace(/=([[{])/g, ':$1')

This produces:

{"response":{"type":0,"products":[{"id":1,"name":"productone"},{"id":2,"name":"producttwo"}],"status":"success"}}

Post a Comment for "Javascript Regular Expression To Wrap Unquoted Json Values (not Keys) With Double Quotes"