我通常不会使用字符串操作来修改 JSON,我会解析 JSON 以获取 JS 对象(在您的情况下为数组数组),然后在转换回 JSON 字符串之前直接修改该对象。
以下是一种方法:
// your input as a string
var input = '[["Management Information Systems","2","0"],["Marketing","1","1"]]';
// parse to get an object that you can manipulate
var obj = JSON.parse(input),
i,
output;
// loop over the array
for (i = 0; i < obj.length; i++){
obj[i][1] = +obj[i][1]; // convert string to number using
obj[i][2] = +obj[i][2]; // the unary plus operator
}
// add the extra element to the beginning of the array
obj.unshift(['Subject', 'Value1', 'Value2']);
// convert to JSON string
output = JSON.stringify(obj);
console.log(output);
// ["Subject","Value1","Value2"],["Management Information Systems",2,0],["Marketing",1,1]]
演示:http://jsfiddle.net/qwoo54rp/
或者你可以使用array .map() method:
var input = '[["Management Information Systems","2","0"],["Marketing","1","1"]]';
var obj = JSON.parse(input).map(function(v) {
return [v[0], +v[1], +v[2]];
}),
output;
obj.unshift(['Subject', 'Value1', 'Value2']);
output = JSON.stringify(obj);
演示:http://jsfiddle.net/qwoo54rp/1/
请注意,您显示的所需格式带有单引号,但尽管这在 JS 对象文字或数组文字中有效,但它不是有效的 JSON。我不使用 Google Graphs,但我会假设它要么需要一个有效的 JSON 字符串(带双引号),要么它需要一个 JS 对象(在这种情况下,引号并不是值的一部分)。
进一步阅读: