1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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)
|