2

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.

0

1 Answer 1

7

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/

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

1 Comment

HttpResponse(df0_js, content_type = 'application/json') is not working for my case

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.