2014-10-06 100 views
1

我試圖創造一些JSON,將渲染蟒蛇/ Django的一個highchart圖形格式的JSON結構。如何創建highcharts與Python

這裏是我的觀點看起來像至今:

class LineHighChart(object): 
    title = {} 

def weight_graph(request): 
    print 'weight graph' 
    highchart = LineHighChart() 
    title = { 
     'title': { 
      'text': 'Weight Chart', 
      'x': -20 
     } 
    } 

    highchart.title = title 
    print highchart 

    return JsonResponse(highchart, safe=False) 

此打印:

<shared.linehighchart.LineHighChart object at 0x1038a6890> 

然後我得到的錯誤:

TypeError: <shared.linehighchart.LineHighChart object at 0x1038a6890> is not JSON serializable 

從highcharts例如,這需要被嵌入在highcharts對象是這樣的:

highcharts({ 
     title: { 
      text: 'Monthly Average Temperature', 
      x: -20 //center 
     }, 

如何讓我的highcharts對象看起來像highcharts例子嗎?

回答

4

您正在嘗試將類的序列化程序對象轉換爲json,但是python不知道如何正確地執行此操作。有幾種方法可以解決此問題:創建自己的對象編碼器,將數據轉換爲字典等。 (more)。

序列號生成後您的數據將是:

'{"title": {"title": {"text": "Weight Chart", "x": -20}}}' 

但是,這是不正確的格式和highcharts會不明白。所以,我建議簡化你的邏輯是這樣的:

def weight_graph(request): 
    title = { 
     'title': { 
      'text': 'Weight Chart', 
      'x': -20 
     } 
    } 

    return JsonResponse(title, safe=False) 

或者,如果你真的需要使用類:

class LineHighChart(object): 
    title = {} 


def weight_graph(): 
    highchart = LineHighChart() 
    title = { 
     'text': 'Weight Chart', 
     'x': -20 
    } 
    highchart.title = title 

    return JsonResponse(highchart.__dict__, safe=False) 

串行數據後會:

'{"title": {"text": "Weight Chart", "x": -20}}' 

Highcharts正常工作與此數據。

0

如果你想在Python中使用highcharts,你應該檢查出python-highcharts,一個python模塊,正是這一點給你。

足夠的文件添加到您開始。 (PIP安裝,IPython的筆記本)