Skip to content

Commit

Permalink
Merge pull request #44 from alingse/add-write-dict-to-xls
Browse files Browse the repository at this point in the history
fix write dict to xls exception
  • Loading branch information
alingse authored Mar 27, 2020
2 parents d05f6e0 + 0d12203 commit eec6a1e
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 11 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ script:
- cat fixture/files/expand.2.json|jsoncsv|mkexcel -t csv > fixture/files/tmp.output.2.csv
- cat fixture/files/raw.1.json|jsoncsv -A|mkexcel > fixture/files/tmp.output.1.csv
- cat fixture/files/raw.1.json|jsoncsv --array|mkexcel > fixture/files/tmp.output.1.csv
- echo '{"a":{}}'|mkexcel -t xls > fixture/files/tmp.output.dict.xls
after_success:
- coveralls
notifications:
Expand Down
23 changes: 13 additions & 10 deletions jsoncsv/dumptool.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,16 +95,16 @@ def write_headers(self):
self.csv_writer.writeheader()

def write_obj(self, obj):
self.csv_writer.writerow(self.patch_obj(obj))
patched_obj = {
key: self.patch_value(value)
for key, value in obj.items()
}
self.csv_writer.writerow(patched_obj)

def patch_obj(self, obj):
new_obj = {}
for key, value in obj.items():
if value in [None, {}, []]:
value = ""

new_obj[key] = value
return new_obj
def patch_value(self, value):
if value in (None, {}, []):
return ""
return value


class DumpXLS(DumpExcel):
Expand All @@ -128,6 +128,9 @@ def write_obj(self, obj):

for head in self._headers:
value = obj.get(head)
# patch
if value in ({},):
value = "{}"
self.ws.write(self.row, self.cloumn, value)
self.cloumn += 1

Expand All @@ -138,7 +141,7 @@ def on_finish(self):


def dump_excel(fin, fout, klass, **kwargs):
if not issubclass(klass, DumpExcel):
if not isinstance(klass, type) or not issubclass(klass, DumpExcel):
raise ValueError("unknow dumpexcel type")

dump = klass(fin, fout, **kwargs)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

setup(
name='jsoncsv',
version='2.2.4',
version='2.2.5',
url='https://github.com/alingse/jsoncsv',
description='A command tool easily convert json file to csv or xlsx.',
long_description=readme,
Expand Down
13 changes: 13 additions & 0 deletions tests/test_dumptool.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,16 @@ def test_dump_xls_with_non_ascii(self):

fin.close()
fout.close()

def test_dump_xls_with_dict(self):
fin = io.StringIO(u'{"a": {}}\n')
fout = io.BytesIO()

dump_excel(fin, fout, DumpXLS)

fin.close()
fout.close()

def test_dump_excel_with_error(self):
with self.assertRaises(ValueError):
dump_excel(None, None, None)

0 comments on commit eec6a1e

Please sign in to comment.