Skip to content

Instantly share code, notes, and snippets.

@adamgreenhall
Forked from ameliagreenhall/df2json.py
Last active October 12, 2019 21:13
Show Gist options
  • Save adamgreenhall/4755513 to your computer and use it in GitHub Desktop.
Save adamgreenhall/4755513 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