我正在尝试根据 webApi 的 json 响应创建线图。我想创建一个时间点数据集,如下所示:
var adddata = {
datasets: [{
label: "a",
backgroundColor: "rgba(255,0,0,0.5)",
fill: false,
data: [{
x: newDateString(0),
y: 22
}, {
x: newDateString(2),
y: 25
}, {
x: newDateString(4),
y: 12
}, {
x: newDateString(5),
y: 22
}],
}, {
label: "b",
backgroundColor: "rgba(0,255,0,0.5)",
fill: false,
data: [{
x: newDate(0),
y: 34
}, {
x: newDate(1),
y: 22
}, {
x: newDate(4),
y: 2
}, {
x: newDate(5),
y: 13
}]
}]
};
现在,如果我有一个如下所示的 json:
{"Values":{"2018-01-17 09:24:34":"0","2018-01-17 09:24:31":"0","2018-01-17 09:24:33":"0","2018-01-17 09:24:35":"0"}}
是否可以创建一个定义各个点的数据集?
最佳答案
您可以解析 JSON 字符串并将生成的 json 对象转换为数据集,如下所示:
var json_str = '{"Values":{"2018-01-16 09:24:34":"10","2018-01-16 19:24:31":"5","2018-01-17 09:24:33":"8","2018-01-18 09:24:35":"9"}}'
var json = JSON.parse(json_str);
var data = [];
for (var d in json.Values) {
console.log(d, json.Values[d]);
data.push({
x : new Date(d),
y : json.Values[d]
})
}
var dataset = {
label : "c",
backgroundColor : "rgba(0,0,255,0.5)",
borderColor : 'green',
fill : false,
data : data
};
// add to existing datasets
adddata.push(dataset);
关于javascript - 从 json 创建一个 Chart.js 点数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48437962/