diff options
author | B Stack <bgstack15@gmail.com> | 2021-01-18 09:51:52 -0500 |
---|---|---|
committer | B Stack <bgstack15@gmail.com> | 2021-01-18 09:51:52 -0500 |
commit | e7c98819e3b5a273b6bcb87883e6c1d15670ae19 (patch) | |
tree | 38acf0edcc3f6bd29b8b616bbfdf890098611883 /j2c.py | |
download | j2c-master.tar.gz j2c-master.tar.bz2 j2c-master.zip |
Diffstat (limited to 'j2c.py')
-rwxr-xr-x | j2c.py | 78 |
1 files changed, 78 insertions, 0 deletions
@@ -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) |