我需要在Kendo图表中显示JSON数据。
我的代码如下,
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.common.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script>
</head>
<body>
<div id="chart"></div>
$("#chart").kendoChart({
series: [{
data: [new Date(formatTime(360)).getTime(), // here 360 means seconds
new Date(formatTime(100)).getTime(),
new Date(formatTime(125)).getTime(),
new Date(formatTime(146)).getTime(),
new Date(formatTime(65)).getTime(),
new Date(formatTime(185)).getTime(),
new Date(formatTime(236)).getTime(),
new Date(formatTime(100)).getTime()],
color: "Blue",
name: "Average time",
type: "line"
},
{
data: [new Date(formatTime(760)).getTime(),
new Date(formatTime(100)).getTime(),
new Date(formatTime(125)).getTime(),
new Date(formatTime(148)).getTime(),
new Date(formatTime(65)).getTime(),
new Date(formatTime(185)).getTime(),
new Date(formatTime(236)).getTime(),
new Date(formatTime(100)).getTime()],
color: "Red",
name: "Wait time",
type: "bar",
}
]
,
valueAxis: {
labels: {
template: "#= kendo.format('{0:HH:mm:ss}', new Date(value)) #"
},
min: new Date("2018/02/01").getTime(),
majorUnit: 10 * 60 * 1000 // 20 minutes step
},
tooltip: {
visible: true,
template: "#= kendo.format('{0:HH:mm:ss}', new Date(value)) #"
}
});
function formatTime(time) {
var rootDate = new Date(new Date(2018, 1, 1, 0, 0, 0).setSeconds(time));
return rootDate;
}
在这里您可以看到,我将静态图表数据设置为data: [new Date(formatTime(360)).getTime()]
,我需要将动态JSOn对象设置为来自JSON对象的图表数据。
我有以下JSON对象。
[{
day: "YYY",
second: "100",
second2: "125"
}, {
day: "XXX",
second: "145",
second2: "117"
}, {
day: "TTT",
second: "565",
second2: "340"
}, {
day: "SSS",
second: "125",
second2: "250"
}]
我从后端分别接收了second
和second2
作为JSON密钥。我需要将这些字段设置为new date
对象作为Chart系列。我该怎么办
假设second
应填充第一个序列(平均时间),second2
应填充第二个序列(等待时间),您可以这样做:
series: [{
data: arr.map(function (o) {
return new Date(formatTime(o.second)).getTime();
}),
color: "Blue",
name: "Average time",
type: "line"
},
{
data: arr.map(function (o) {
return new Date(formatTime(o.second2)).getTime();
}),
color: "Red",
name: "Wait time",
type: "bar",
}]
...其中arr
是您从后端获得的数组(当然是从JSON转换之后)。
[如果您正在考虑获取一个新的javascript值来解析一些包含js代码的字符串,只需运行eval
函数并使其神奇即可。检查此代码:
let x = 'new Date()';
console.log(eval(x))