Skip to content

Latest commit

 

History

History
58 lines (36 loc) · 2.03 KB

Pandas_Transform_DataFrame_to_json_file.md

File metadata and controls

58 lines (36 loc) · 2.03 KB



Template request | Bug report | Generate Data Product

Tags: #pandas #dataframe #json #transform #file #dict #snippet

Author: Florent Ravenel

Description: This notebook will show how to transform a DataFrame into a json file. It is usefull for organizations that need to store data in a json format.

References:

Input

Import libraries

import pandas as pd
import json

Setup Variables

  • orient : Determines the type of the values of the dictionary ('dict', 'list', 'series', 'split', 'tight', 'records', 'index')
  • df: fake DataFrame
  • json_path: json file path
orient = "records"
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
json_path = "data.json"

Model

Transform DataFrame to dict

# Transform DataFrame to json
data = df.to_dict(orient=orient)
data

Output

Save dict to JSON

with open(json_path, "w") as f:
    json.dump(data, f)
print("The json file has been saved to the current directory.")