簡體   English   中英

如何使用python創建highcharts格式的json結構

[英]how to create highcharts formatted json structure with python

我正在嘗試創建一些將使用python / django渲染highchart圖的json。

到目前為止,這是我的看法:

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示例?

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

序列化后,您的數據將是:

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

但這是不正確的格式,高圖將無法理解。 因此,我建議您簡化邏輯,如下所示:

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可以很好地處理此數據。

如果要在python中使用highcharts,則應查看python-highcharts ,這是一個為您執行此操作的python模塊。

添加了足夠的文檔來幫助您入門。 (pip安裝,ipython筆記本)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM