用JavaScript RegEx替换嵌套的双引号

时间:2015-09-15 06:42:35

标签: javascript json regex

我有一个JSON字符串化的对象,如下所示。我需要使用JSON.parse解析对象。我正面临嵌套的双引号,我想用RegEx代替。

// input string 
var stringifyObj = '{
"a": "abcd"",
  "b": false,
  "c": [
    {
      "c": "1234",
      "d": "abcd",
      "e": [
        {
          "cs": "cs",
          "df": true
        }
      ],
      "g": "USE",
      "f": false,
      "g": "QA DCG",
      "h": "333 Market St",
      "i": "San Francisco",
      "j": " 94568"
    },
    {
      "k": "20570",
      "l": "test",
      "m": [
        {
          "n": "USD",
          "o": true
        }
      ],
      "p": "US",
      "q": true,
      "r": "Wires_defect 13205 testing",
      "s": "333 market street_retesting 13205",
      "t": "SF_test",
      "u": "ABCD"",
      "v": false
    }
  ]
}';

如何解析此stringify对象“a和u”属性包含嵌套的双引号。

我尝试替换但不起作用:replace(/(".*?"):(".*?)"(.*?")/g,"$1:$2\\\"$3")

1 个答案:

答案 0 :(得分:0)

取决于String中预期的值,引号数,特殊字符等等......

但是对于这种特殊情况,您可以使用它,或者至少将其用作起点

var bad_json_string = '{"a":"abc"@#"}';
var cleaned_string = bad_json_string.replace(/([^:]+:")(.*)"(.*"})/g, function(){return RegExp.$1 + RegExp.$2 +"'"+ RegExp.$3 });

document.write(cleaned_string);
//    tested on Win7 with chrome 44+

更新1:

使用javascript RegExp Expression无法轻松修复更新后的json。使用嵌套的List / Objects /...

我建议从服务器清理Json,如果这不可能,我会写一个函数以另一种方式“解析”字符串。

更新2:

一个可能的功能解决方案可能/应该是这个(只是快速演示,审核/ 优化用于生产用途

var bad_json_string = '{\r\n"a": "abcd"",\r\n  "b": false,\r\n  "c": [\r\n    {\r\n      "c": "1234",\r\n      "d": "abcd",\r\n      "e": [\r\n        {\r\n          "cs": "cs",\r\n          "df": true\r\n        }\r\n      ],\r\n      "g": "USE",\r\n      "f": false,\r\n      "g": "QA DCG",\r\n      "h": "333 Market St",\r\n      "i": "San Francisco",\r\n      "j": " 94568"\r\n    },\r\n    {\r\n      "k": "20570",\r\n      "l": "test",\r\n      "m": [\r\n        {\r\n          "n": "USD",\r\n          "o": true\r\n        }\r\n      ],\r\n      "p": "US",\r\n      "q": true,\r\n      "r": "Wires_defect 13205 testing",\r\n      "s": "333 market street_retesting 13205",\r\n      "t": "SF_test",\r\n      "u": "ABCD"",\r\n      "v": false\r\n    }\r\n  ]\r\n}';

var t = bad_json_string.match(/^(.| )*$/gm);

function unQuote(string){
	return string.replace(/^"/,"").replace(/"$/,"");
}

function trim(string, chr){
	return string.replace(new RegExp("^(" + (chr || " " )+")*"),"").replace(new RegExp( "(" + (chr || " ") + ")*$"),"");
}

var clean = "";

function buildObj(list, idx){

	if(list.length<=idx)
		return;
		
    var item = trim(list[idx]);
	
	switch(item){
		case "{":
		case "[":
		case "}":
		case "]":
		case "},":
		case "],":
			clean += item;
			break;
		case "":
			break; 
		default: 
			var line = item.split(":");
			var index = unQuote(line[0]);
			var value = trim(trim(line[1]),",");
			clean += index + ":";
			
			if(value.indexOf("\"")==0){
				clean += "'"+ unQuote(value) + "',";
			}
			else if(value.indexOf("{")==0 || value.indexOf("[")==0){
				clean += value;
			}
			else{
				clean += value + ",";
			}
			
	}

	buildObj(list, ++idx);
}


buildObj( t, 0);

document.write(clean);
// to get the object you could do this, but dont forget eval==evil. :)
 var t;
 eval("t="+clean);
 document.write("<br/><br/><br/>");
 document.write("Object prop 'a' => " + t['a']);
// tested on Win7 with Chrome 44+