Code Ninja Code Ninja - 6 months ago 23
JSON Question

How to return json using Flask web framework

My aim is to do data summary in python using Pandas and return the summary in the form of JSON. I am using the Flask web framework to return JSON.



My code to get JSON is as follows:(excluding libraries)

data = pandas.read_csv('D:\myfile.csv')
for colname, dtype in data.dtypes.to_dict().iteritems():
if dtype == 'object':
print colname
count = data[colname].value_counts()
d = dict((str(k), int(v)) for k, v in count.iteritems())
f = dict(sorted(d.iteritems(), key=lambda item: item[1], reverse = True)[:5])
print f
json.dumps(f)


In Flask I have to do the following things:

@app.route("/summary")
def some_fn():
# identify filename

# do summary on file

# send it back as json

Answer

If f is your dictionary, you can just do

return flask.jsonify(**f)