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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.