JPC
JPC

Reputation: 5173

how to convert pandas dataframe to json to use in django template

I'm trying to create json from dataframe

response_data = [
        { "x_axis": 30,  "y_axis":  30, "radius": 20, "color": "green" },
        { "x_axis": 70,  "y_axis":  70, "radius": 20, "color": "green" },
        { "x_axis": 110, "y_axis": 100, "radius": 20, "color": "blue" }
    ]
    result = HttpResponse(json.dumps(response_data), content_type = 'application/json')

If I use above I would get

Content-Type: application/json [{"color": "green", "y_axis": 30, "x_axis": 30, "radius": 20}, {"color": "green", "y_axis": 70, "x_axis": 70, "radius": 20}, {"color": "blue", "y_axis": 100, "x_axis": 110, "radius": 20}] 

which is exactly format that I want , but if I try to do it from dataframe using something like :

d = {'one' : pd.Series([1., 2., 3.]),'two' : pd.Series([1., 2., 3., 4.])}
df0_fa = pd.DataFrame(d)
df0_js = df0_fa.to_json()
result2 = HttpResponse(json.dumps(df0_js), content_type = 'application/json')

I got this json format :

Content-Type: application/json "{\"one\":{\"0\":1.0,\"1\":2.0,\"2\":3.0,\"3\":null},\"two\":{\"0\":1.0,\"1\":2.0,\"2\":3.0,\"3\":4.0}}" 

But I what I really want is

Content-Type: application/json [{"one" : 1.0,"two" :1.0},{"one" : 2.0,"two" :2.0},{"one" : 3.0,"two" :3.0},{"one" : null,"two" :4.0}]

what's backslash do in here ? and [] I have tried different orient setting but doesn't work. any recommendation would be appreciated. thanks.

Upvotes: 2

Views: 5214

Answers (1)

Jonathan M
Jonathan M

Reputation: 17451

You're double converting it to JSON. df0_fa.to_json() is doing it, then json.dumps() is doing it. Just do: result2 = HttpResponse(df0_js, content_type = 'application/json')

Some notes on to_json(): http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.html

A good page on json.dumps(): http://www.pythonforbeginners.com/python-on-the-web/parsingjson/

Upvotes: 7

Related Questions