解析字符串并删除空格和换行并转换为json OBJECT

时间:2016-01-21 14:21:12

标签: javascript arrays json

我有以下方式的字符串如何将此字符串转换为JSON对象..我的字符串是

{\"Warranty\": [ \n { \n \"Name\": \"test\", \n \"Type\": \"test2\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"Test6\", \n \"Type\": \"test7\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"test9\", \n \"Type\": \"test10\", \n \"Miles\": \"10000\", \n } \n ]}

请帮助将上面的字符串转换为JSON对象。

我尝试使用以下代码但仍然得到字符串值而不是对象

  var body = " {\"Warranty\": [ \n { \n \"Name\": \"test\", \n \"Type\": \"test2\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"Test6\", \n \"Type\": \"test7\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"test9\", \n \"Type\": \"test10\", \n \"Miles\": \"10000\", \n } \n ]} ".replace(/\r?\n|\r/g, "").replace(/\s+/g, "");
    var json=body.replace(/['"]+/g, '');
    var object = JSON.stringify(json);
    object = JSON.parse(object)

2 个答案:

答案 0 :(得分:0)

如果(并且仅当)您确定该字符串不包含任何恶意部分(即,您确定数据的来源及其完整性),那么使用{{}可能是最容易的。 1}}:

eval

答案 1 :(得分:0)

正如dfsq建议的那样,在解析之前删除结束括号(})之前的逗号(,):

var body = " {\"Warranty\": [ \n { \n \"Name\": \"test\", \n \"Type\": \"test2\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"Test6\", \n \"Type\": \"test7\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"test9\", \n \"Type\": \"test10\", \n \"Miles\": \"10000\", \n } \n ]} ".replace(/\r?\n|\r/g, "").replace(/\s+/g, "").replace(/,}/g,'}');
var object = JSON.parse(body);

或者不删除额外的空格和换行符:

var body = " {\"Warranty\": [ \n { \n \"Name\": \"test\", \n \"Type\": \"test2\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"Test6\", \n \"Type\": \"test7\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"test9\", \n \"Type\": \"test10\", \n \"Miles\": \"10000\", \n } \n ]} ".replace(/,\s*}/g,'}');
var object = JSON.parse(body);