[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Can anybody help me retrieve how to retrieve output from this Python code below!

ksatish.dtc at gmail.com wrote:

[snip code]

Wasn't there any documentation to go with that script? That's the preferable 
method to use software written by someone else ;)

Anyway -- First you have to undo what was probably changed by yourself:

$ diff -u json2csv_orig.py json2csv.py
--- json2csv_orig.py    2017-07-11 15:15:06.527571509 +0200
+++ json2csv.py 2017-07-11 15:14:17.878514787 +0200
@@ -132,14 +132,6 @@
     return parser
-json_file = input("Type Json input file name: ")
-key_map = input("Type Key value : ")
 if __name__ == '__main__':
     parser = init_parser()
@@ -159,4 +151,4 @@
         fileName, fileExtension = os.path.splitext(args.json_file.name)
         outfile = fileName + '.csv'
-loader.write_csv(filename=outfile, make_strings=args.strings)
+    loader.write_csv(filename=outfile, make_strings=args.strings)

Then you have to create a file containing the data in json format, e. g.

$ cat data.json
    ["alpha", "beta", {"one": {"two": "gamma"}}],
    ["zeta", "eta", {"one": {"two": "theta"}}]

...and a file describing the conversion, also in json, like

$ cat key_map.json
   "map": [
       ["foo", "0"],
       ["bar", "1"],
       ["baz", "2.one.two"]

Now you can run the script, first to look at the command line help

$ python json2csv.py -h
usage: json2csv.py [-h] [-e] [-o OUTPUT_CSV] [--strings] json_file key_map

Converts JSON to CSV

positional arguments:
  json_file             Path to JSON data file to load
  key_map               File containing JSON key-mapping file to load

optional arguments:
  -h, --help            show this help message and exit
  -e, --each-line       Process each line of JSON file separately
  -o OUTPUT_CSV, --output-csv OUTPUT_CSV
                        Path to csv file to output
  --strings             Convert lists, sets, and dictionaries fully to 
comma-separated strings.

and then to process your data:

$ python json2csv.py data.json key_map.json
INFO:root:[u'alpha', u'beta', {u'one': {u'two': u'gamma'}}]
INFO:root:[u'zeta', u'eta', {u'one': {u'two': u'theta'}}]

Finally, let's have a look at the resulting csv file:

$ cat data.csv