以json对象的形式传递时间戳值以填充流线图


passing timestamps value in form of json object to populate flot charts

我试图通过从MongoDb查询不同时间戳的值,然后以JSON的形式将它们传递给客户端。

然后客户端将读取php脚本返回的JSON对象,并在此基础上填充流程图。

我不能这样做,我有以下两个疑问/问题:

在php返回的JSON对象中,应该如何构造JSON对象?

目前,从下面的代码中,生成的JSON如下:
[{"1371859200000":65},{"1371860100000":63},{"1371861000000":48},{"1371861900000":47},{"1371862800000":41},{"1371863700000":19},{"1371864600000":35}]

以上内容正确吗?或者数据应该是这样的:[["1371859200000":65],["1371860100000":63],....]

两者的区别是什么?(上面用'['代替大括号)

B。在PHP中,strtotime返回int。但是,当我回显我的JSON对象时,时间戳产生为"1371859200000"(即字符串)而不是1371859200000(即int)。为什么呢?我必须填充流线图,为了填充流线图,时间戳必须以int(而不是字符串)形式呈现。

以下是我的PHP代码(不是全部代码):

$date = 2;
$tsc = 15;
$result = array();
for ($hour = 0; $hour  < 24; $hour++) {
    for ($min_lower = 0; $min_lower <= 60-$tsc; $min_lower += $tsc) {
        // Query MongoDB.
        $query = array( "date" => $date, "hour" => $hour, "minutes" => array( '$gte' => $min_lower, "'$lt" => $min_lower+$tsc ) );
        $count = $coll->find($query)->count();
        $time = strtotime("2013-06-".strval($date)." ".strval($hour).":".strval($min_lower).":".strval(0)." UTC") * 1000;
        $data = array($time => $count);
        // Push this smaller array into the main array. Is this the correct way ?
        array_push($result, $data);
    }
}
echo json_encode($result);

下面是我的javascript/jquery代码:

var options = {
    lines: {
        show: true
    },
    points: {
        show: true
    },
    xaxis: {
        mode : "time",
        timeformat: "%m/%d/%y"
     }
};
$("button.fetch").click(function () {
    var button = $(this);
    var dataurl = "MY URL";// Here the URL comes.
    function onDataReceived(series) {
        data.push(series);
        $.plot("#placeholder", series, options);
    }
    $.ajax({
        url: dataurl,
        type: "GET",
        dataType: "json",
        success: onDataReceived
    });
 })

[[key: value]]是无效的JavaScript或JSON语法。对象只能使用键值对,即花括号语法。

B。同样,对象键也只能是字符串,不能是数字。有{123: "value"}是无效的JSON语法,它必须是{"123": "value"}

两种可能的解决方案是

  1. 在JS端简单地将键转换为数字;你可能会依赖于这样一个事实:它们总是数字
  2. 以不同的方式表示数据,如[{"ts": 13456000, "count": 65}],因为值可以是数字,即使键不能。