1

I am trying to create some json that will render a highchart graph with python/django.

here is what my view looks like so far:

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)

This prints:

<shared.linehighchart.LineHighChart object at 0x1038a6890>

I then get the error:

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

From the highcharts example, this needs to be embedded in a highcharts object like this:

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

How do I make my highcharts object look like the highcharts example?

Alex Lisovoy
  • 5,767
  • 3
  • 27
  • 28
Atma
  • 29,141
  • 56
  • 198
  • 299

2 Answers2

4

You are trying serializer object of class to json, but python doesn't know how do this correctly.There are several approaches to solving this problem: create your own object encoder, converting data into a dictionary, etc...(more).

After serialization your data will be:

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

But this is incorrect format and highcharts will not understand it. So I propose simplified you logic like this:

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

    return JsonResponse(title, safe=False)

Or if you really need use class:

class LineHighChart(object):
    title = {}


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

    return JsonResponse(highchart.__dict__, safe=False)

After serialization data will be:

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

Highcharts works fine with this data.

Community
  • 1
  • 1
Alex Lisovoy
  • 5,767
  • 3
  • 27
  • 28
0

If you want to use highcharts in python, you should check out python-highcharts, a python module which does exactly this for you.

Sufficient documentation is added to get you started. (pip install, ipython notebook)

mvdc7070
  • 23
  • 3