python传递数组结构以查看为json

时间:2015-03-11 03:08:35

标签: jquery python arrays json plugins

Python API returns the following data when requested::

x_values = [
  [0,'10:00:00 AM'],
  [1,'10:00:10 AM'],
  [2,'10:00:10 AM'],
  [3,'10:00:20 AM']
]
y_values = [
  [0,3],
  [1,0],
  [2,3],
  [3,1]
]
data = {
  "x":x_values,
  "y":y_values
}
self.send_json(data)

这是使用Python 2.7.9的api。以下是jquery脚本。

$('.flot-graph').each(function() {
    var graph_drawing_area = $(this);
    $.ajax({
        url: '/api/get/data', // call the api
        success: function(data){
            var y = JSON.stringify(data['y']);
            var x = JSON.stringify(data['x']);
            var graph_data = [
                {
                    data: y
                }    
            ];
            var options = {
                xaxis: {
                    ticks:x
                }
            };
            return $.plot(graph_drawing_area, graph_data, options); 
        },
        error: function(){
            alert('failure');
        }
    });

});

这应该在类名为'flot-graph'的div上绘制图表。我现在遇到的问题是我需要重新生成与python中完全相同的数组结构。换句话说,jquery脚本必须类似于

success: function(data){
...
    var graph_data = [{
        //note that y is decoded and replaced as array format
        data: [
           [0,3],
           [1,0],
           [2,3],
           [3,1]
        ]
    }];
    var options = {
        //note that x is decoded and replaced as array format
        xaxis: {
            ticks:[
               [0,'10:00:00 AM'],
               [1,'10:00:10 AM'],
               [2,'10:00:10 AM'],
               [3,'10:00:20 AM']
            ]
        }
    };
    return $.plot(graph_drawing_area, graph_data, options); 
},
.......

我尝试使用JSON.stringify,但似乎没有重新生成数组。此外,JSON.parse()没有给我我想要的东西,但是一堆“Uncaught SyntaxError:Unexpected token u”错误 - 我认为解析后的返回值不是一个合适的选项。

我该如何解决这个问题?如果我的方法不是最好的,那么在这种情况下更合适的是什么?

感谢。

1 个答案:

答案 0 :(得分:0)

我根本不需要解析它......多么愚蠢:'(