From e7c98819e3b5a273b6bcb87883e6c1d15670ae19 Mon Sep 17 00:00:00 2001 From: B Stack Date: Mon, 18 Jan 2021 09:51:52 -0500 Subject: initial commit --- j2c.py | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100755 j2c.py (limited to 'j2c.py') diff --git a/j2c.py b/j2c.py new file mode 100755 index 0000000..936d47c --- /dev/null +++ b/j2c.py @@ -0,0 +1,78 @@ +#!/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) -- cgit