#!/usr/local/cpython-3.6/bin/python3 """Convert a JSON list-of-nonnested-dicts to CSV.""" import csv import sys import json def main(): """Read JSON, output CSV.""" # Read JSWON data, convert to list of dicts json_data = json.loads(sys.stdin.read()) if not isinstance(json_data, list): raise ValueError('Input must be a JSON list') # Get a list of all keys (not just the keys in the first dict) keys = set() for dict_ in json_data: if not isinstance(dict_, dict): raise ValueError("Input must be a JSON list of dict's") for key in dict_: keys.add(key) # Sort the keys key_list = [key.strip() for key in keys] key_list.sort() # Write as CSV. csv_writer = csv.writer(sys.stdout, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator='\n') csv_writer.writerow(key_list) for dict_ in json_data: # Build a list of values to output list_ = [] for key in key_list: value = dict_.get(key, '') if isinstance(value, (int, float, bool)): value = str(value) list_.append(value.strip()) # And output it.as possibly-quoted CSV csv_writer.writerow(list_) main()