Permalink
Browse files

Supposedly support Python 2 and Python 3.

O know very little about python but this seems to be working:

```
cd JSON2CSV
virtualenv -p python2 PY2-env
. PY2-env/bin/activate
python setup.py install
json2csv ../test_file.json ../test_file.csv
cat ../test_file.csv
rm build/ dist/ json2csv.egg-info/ -rf
deactivate

virtualenv -p python3 PY3-env
. PY3-env/bin/activate
python setup.py install
json2csv ../test_file.json ../test_file.csv
cat ../test_file.csv
rm build/ dist/ json2csv.egg-info/ -rf
deactivate
```
  • Loading branch information...
Arjuna Del Toso
Arjuna Del Toso committed Oct 26, 2017
1 parent 52d91ab commit 3a1aff97681bb6ed5e59b70782dead95aba28202
Showing with 18 additions and 8 deletions.
  1. +18 −8 json2csv/api.py
View
@@ -1,10 +1,12 @@
import csv
import json
import logging
from itertools import chain
import json
import csv
from six import string_types
from six import string_types, PY2
logger = logging.getLogger("json2csv")
JSONError = ValueError if PY2 else json.decoder.JSONDecodeError
def json_to_csv(input_file_path, output_file_path):
@@ -18,7 +20,7 @@ def json_to_csv(input_file_path, output_file_path):
def json_to_dicts(json_str):
try:
objects = json.loads(json_str)
except json.decoder.JSONDecodeError:
except JSONError:
objects = [json.loads(l) for l in json_str.split('\n') if l.strip()]
return [dict(to_keyvalue_pairs(obj)) for obj in objects]
@@ -50,12 +52,20 @@ def build_row(dict_obj, keys):
cw = csv.writer(output_file)
cw.writerow(keys)
for row in rows:
cw.writerow([c.encode('utf-8') if isinstance(c, str) or isinstance(c, unicode) else c for c in row])
if PY2:
for row in rows:
cw.writerow([c.encode('utf-8') if isinstance(c, str) or isinstance(c, unicode) else c for c in row])
else:
for row in rows:
cw.writerow([c for c in row])
def write_csv(headers, rows, file):
cw = csv.writer(file)
cw.writerow(headers)
for row in rows:
cw.writerow([c.encode('utf-8') if isinstance(c, str) or isinstance(c, unicode) else c for c in row])
if PY2:
for row in rows:
cw.writerow([c.encode('utf-8') if isinstance(c, str) or isinstance(c, unicode) else c for c in row])
else:
for row in rows:
cw.writerow([c for c in row])

0 comments on commit 3a1aff9

Please sign in to comment.