#!/usr/bin/env python3 # File: j2c.py # Location: https://gitlab.com/bgstack15/j2c # Author: bgstack15 # Startdate: 2021-01-16 # SPDX-License-Identifier: CC-BY-SA-4.0 # Title: Json To CSV Library for Python # Purpose: NIH # History: # Usage: # Reference: # Improve: # Documentation: # vim: set ts=3 sw=3 sts=3 et: import json, sys, os # default debug level for this library debug = 0 def load_json_file(filename): _lof=[] with open(filename,"r") as f: _lof = json.load(f) return _lof def debugprint(dstring,debug=debug): if debug >= 1: print(dstring) def print_json(json_obj,indent=1): print(json.dumps(json_obj,indent=indent)) def convert_json_to_csv(json_objorfile,csvfile="stdout",debug=debug): try: if os.path.exists(json_objorfile): json_obj = load_json_file(json_objorfile) except: json_obj = json_objorfile print("json_obj=",json_obj) # Learn keys at this level keys=[] for i in json_obj: for j in list(i.keys()): if j not in keys: keys.append(j) debugprint("Found key {0}".format(j),debug=debug) #for k in keys: # print(k) x=0 fullstring="" for i in json_obj: x += 1 # only if there are actually contents of "all" do we print the headers if x == 1: for k in keys: fullstring += str(k) + "," fullstring += "\n" for k in keys: p = "" try: p = str(i[k]).replace(",",":") except: # no value for this key for this entry pass pp = "{0},".format(p) fullstring += pp fullstring += "\n" if fullstring != "": if csvfile == "stdout": print(fullstring) else: with open(csvfile,"a") as of: of.write(fullstring)