Search code examples
javascriptjsonnode.jsregexhashmap

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 to get it from this:

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

to this:

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

using the following regexes:

hashmap  =  hashmap
        .replace (/ /g,"").replace(/\s/g,"")                    //replace all spaces
        .replace (/'/g,"").replace(/"/g,'')                     //replace all quotes
        .replace(/=/g,":")                                      //replace = with :
        .replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"$2": ');  //put quotes around keys

How would I go around wrapping the values with double quotes using a regex. Any help is highly appreciated.

EDIT :

I would eventually want it to be in this form :

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

Solution

  • 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"}}