简体   繁体   English

Javascript正则表达式用双引号将未引号的JSON值(NOT键)包装起来

[英]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. 我一直在尝试用双引号包装一些格式错误的JSON值。 The response is from a Java Servlet (its actually a hashmap) which I have no control over. 响应来自我无法控制的Java Servlet(实际上是一个哈希图)。 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"}}

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: 现在,您可以使用以下命令将其转换为JavaScript对象:

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: 但是,更符合JSON解析的方法不是引用数字值,而是将它们解析为数字,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM