Questions Json to csv solution

Questions Json to csv solution

eliantis

User
User ID
50146
Feb 17, 2024
99
11
#CR
0
  • Thread starter
  • Thread Author
  • #1
Hello everyone,
I'm looking for free software to convert databases from JSON to CSV format.
There are quite a few Python scripts, but they're not always reliable.
Do you have a solution to share, or at best, free software for Linux or Windows?
Thank you for your help.
 
In my opinion, I prefer work with JSON file, but if you want to transform files, this code can be used, not really tested so you can add some modifications:
Python:
# json_to_csv.py

import json
import csv
import argparse
import sys

def flatten_json(y, prefix=''):
    """Recursively flattens a nested dictionary."""
    out = {}
    for key, value in y.items():
        full_key = f"{prefix}.{key}" if prefix else key
        if isinstance(value, dict):
            out.update(flatten_json(value, prefix=full_key))
        else:
            out[full_key] = value
    return out

def json_to_csv(json_file_path, csv_file_path):
    try:
        with open(json_file_path, 'r', encoding='utf-8') as json_file:
            data = json.load(json_file)

        if not isinstance(data, list):
            raise ValueError("JSON must be a list of objects (dictionaries).")

        flattened_data = [flatten_json(item) for item in data]

        headers = sorted(set().union(*(item.keys() for item in flattened_data)))

        with open(csv_file_path, 'w', newline='', encoding='utf-8') as csv_file:
            writer = csv.DictWriter(csv_file, fieldnames=headers)
            writer.writeheader()
            for row in flattened_data:
                writer.writerow(row)

        print(f"Successfully converted to: {csv_file_path}")

    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)

def main():
    parser = argparse.ArgumentParser(description='Convert a JSON file to CSV (with nested fields flattened).')
    parser.add_argument('json_input', help='Path to the input JSON file')
    parser.add_argument('csv_output', help='Path to the output CSV file')

    args = parser.parse_args()
    json_to_csv(args.json_input, args.csv_output)

if __name__ == '__main__':
    main()

Usage: python json_to_csv.py /path/to/file.json /path/to/output.csv
 
could also just use pandas


Python:
import sys
import pandas as pd

infile = sys.argv[1]

df = pd.read_json(infile)
# flattened json could also be done
#import json
#data_dict = json.load(open(infile))
#df = pd.json_normalize(data_dict)

df.to_csv(infile.replace('.json','.csv'), index=False)
 
Back
Top Bottom