我有一个responseText
作为字符串,格式如下:
[['0.00',4474.12], ['31.25',1995.16], ['62.50',44.98], ['93.75',16.86], ['125.00',9.10], ['156.25',5.76], ['187.50',3.99], ['218.75',2.92], ['250.00',2.21], ['281.25',1.71], ['312.50',1.33], ['343.75',1.03], ['375.00',0.77], ['406.25',0.56], ['437.50',0.36], ['468.75',0.18]]
我想将其更改为数组以提供Google Charts API中的addRows()
函数。
您能帮助我使用JavaScript吗?
非常感谢您。
答案 0 :(得分:2)
您可以使用JSON.parse()
,但是由于您拥有 single quotation
,因此您在JSON.parse()
中将其视为syntax error需要先将它们替换掉,否则您就不应该去了。
console.log( JSON.parse(`[1,2,3]`))
console.log( JSON.parse(`["1",2]`))
console.log( JSON.parse(`['1',2]`)) // error on this line
工作代码
let str = `[['0.00',4474.12], ['31.25',1995.16], ['62.50',44.98], ['93.75',16.86], ['125.00',9.10], ['156.25',5.76], ['187.50',3.99], ['218.75',2.92], ['250.00',2.21], ['281.25',1.71], ['312.50',1.33], ['343.75',1.03], ['375.00',0.77], ['406.25',0.56], ['437.50',0.36], ['468.75',0.18]]`
let op = JSON.parse(str.replace(/'/g,`"`))
console.log(op)
答案 1 :(得分:1)
您可以使用JSON.parse
将文本转换为数组
(如其他问题所述,如果您将单引号替换为双引号)
var text = xhr.responseText;
var arrData = JSON.parse(text);
data.addRows(arrData);
编辑
如果您的数据被格式化为json对象,
您可以将其转换为Google图表的简单数组,
使用for...in
语句。
请参阅以下工作片段...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var jsonData = {"0.00" : 3717.22, "31.25" : 1657.63, "62.50" : 37.37, "93.75" : 14.00, "125.00" : 7.56, "156.25" : 4.79, "187.50" : 3.32, "218.75" : 2.43, "250.00" : 1.84, "281.25" : 1.42, "312.50" : 1.10, "343.75" : 0.85, "375.00" : 0.64, "406.25" : 0.46, "437.50" : 0.30, "468.75" : 0.15};
var arrayData = [];
// convert json to simple array for google charts
for (var x in jsonData) {
if (jsonData.hasOwnProperty(x)) {
arrayData.push([
x,
jsonData[x]
]);
}
}
// convert array to google data table
// be sure to pass true for "first row is data" argument
var data = google.visualization.arrayToDataTable(arrayData, true);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>