'Convert JSON to CSV Python - Command Line

I'm a novice at coding, so forgive me but sometimes I need a step-by-step walkthrough. I have a large JSON file (544 MB) that I need to convert to CSV. I have code from another forum to run in VS Code (below). But now I'm not sure what to type in Terminal to actually do the conversion for multiple similar files I need to convert.

Here's the code I have, json-convert.py:

from copy import deepcopy
import pandas
import json


def cross_join(left, right):
    new_rows = [] if right else left
    for left_row in left:
        for right_row in right:
            temp_row = deepcopy(left_row)
            for key, value in right_row.items():
                temp_row[key] = value
            new_rows.append(deepcopy(temp_row))
    return new_rows


def flatten_list(data):
    for elem in data:
        if isinstance(elem, list):
            yield from flatten_list(elem)
        else:
            yield elem


def json_to_dataframe(data_in):
    def flatten_json(data, prev_heading=''):
        if isinstance(data, dict):
            rows = [{}]
            for key, value in data.items():
                rows = cross_join(rows, flatten_json(value, prev_heading + '.' + key))
        elif isinstance(data, list):
            rows = []
            for i in range(len(data)):
                [rows.append(elem) for elem in flatten_list(flatten_json(data[i], prev_heading))]
        else:
            rows = [{prev_heading[1:]: data}]
        return rows

    return pandas.DataFrame(flatten_json(data_in))

if __name__ == '__main__':
    f = open('pretty-202009.json')
    json_data = json.load(f)
    df = json_to_dataframe(json_data)
    df.to_csv("flight_csv.csv", sep=',', encoding='utf-8')


    # run  in terminal for conversion to csv


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source