Last active
July 7, 2023 13:08
-
-
Save pozemka/ba53a6e6dadccc3233994f6f53ca5605 to your computer and use it in GitHub Desktop.
json to csv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
__copyright__ = "2023, pozemka" | |
__license__ = "WTFPL" | |
import argparse | |
import json | |
import pandas | |
from pathlib import Path | |
parser = argparse.ArgumentParser(description='Convert JSON to CSV.') | |
parser.add_argument('JSON', type=str, help='Input JSON') | |
parser.add_argument('CSV', type=str, help='Output CSV') | |
args = parser.parse_args() | |
in_path = Path(args.json) | |
out_path = Path(args.CSV) | |
with in_path.open('r', encoding='utf-8') as f: | |
data = json.loads(f.read()) | |
top_level_keys = list(data.keys()) | |
if len(top_level_keys) == 1 : | |
data = data[top_level_keys[0]] | |
dataframe = pandas.json_normalize(data) | |
dataframe.to_csv(out_path, index=False, encoding='utf-8') | |
# More info about pandas JSON normalization: | |
# https://github.com/BindiChen/machine-learning/blob/main/data-analysis/028-pandas-json_normalize/pandas-json_normalize.ipynb |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment