将json字符串转换为数组格式,可用于图表数据

时间:2015-01-21 11:30:45

标签: javascript jquery json

实际数据:

 var x =" [{ name: 'Chintan test', data: [3, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0] }, 
{ name: 'Lara Black &White', data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, 
{ name: 'kamlesh ', data: [1, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0] }, { name: 'Gopala lalalala', data: [1, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0] }, 
{ name: 'Saurin Test ', data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }]";

如何转换所以我可以得到以下结果:

var y = [{ name: 'Chintan test', data: [3, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0] }, 
{ name: 'Lara Black &White', data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, 
{ name: 'kamlesh ', data: [1, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0] }, { name: 'Gopala lalalala', data: [1, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0] }, 
{ name: 'Saurin Test ', data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }]

我做了什么:

尝试1:

y=x.substring(1,x.length-1);  // not helpfull

尝试2:

y = JSON.parse(x);  //  SyntaxError: JSON.parse: expected property name or '}' at line 1 column 5 of the JSON data

2 个答案:

答案 0 :(得分:0)

这不是有效的JSON,主要是因为JSON要求属性名称用引号括起来。在属性名称周围添加引号后,它看起来应该是可解析的。

答案 1 :(得分:0)

字符串无效JSON(你可以在这里查看http://jsonlint.com/),所以为了解析它你首先需要用有效的JSON转换它。

为了使它成为有效的JSON,属性名称应该用双引号封装(name:=>" name" :)并且字符串也是如此(' Chintan test' ; =>" Chintan test")。您可以使用一些字符串替换来执行此操作:

var x =" [{ name: 'Chintan test', data: [3, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0] }, { name: 'Lara Black &White', data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'kamlesh ', data: [1, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0] }, { name:'Gopala lalalala', data: [1, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0] }, { name: 'Saurin Test ', data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }]";

x = x.replace(/data:/g, '"data":'); //name attribute data to "data"
x = x.replace(/name:/g, '"name":'); //name attribute name to "name"
x = x.replace(/:\s*'(.+?)'/g, ':"$1"'); // :'string' to :"string"

var y = JSON.parse(x);

请注意,x内的字符串不应包含新行。

jsfiddle工作示例:http://jsfiddle.net/jx3opp8g/