Skip to content

Instantly share code, notes, and snippets.

@michaelfeng
Forked from adamgreenhall/df2json.py
Created April 19, 2018 16:39
Show Gist options
  • Save michaelfeng/79291c46dd6516b1baefa4aa75c27355 to your computer and use it in GitHub Desktop.
Save michaelfeng/79291c46dd6516b1baefa4aa75c27355 to your computer and use it in GitHub Desktop.
Convert pandas.DataFrame to JSON (and optionally write the JSON blob to a file).
"""
tiny script to convert a pandas data frame into a JSON object
"""
import json as json
def df_to_json(df, filename=''):
x = df.reset_index().T.to_dict().values()
if filename:
with open(filename, 'w+') as f: f.write(json.dumps(x))
return x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment