Skip to content

Commit eec6a1e

Browse files
authored
Merge pull request #44 from alingse/add-write-dict-to-xls
fix write dict to xls exception
2 parents d05f6e0 + 0d12203 commit eec6a1e

File tree

4 files changed

+28
-11
lines changed

4 files changed

+28
-11
lines changed

.travis.yml

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ script:
2121
- cat fixture/files/expand.2.json|jsoncsv|mkexcel -t csv > fixture/files/tmp.output.2.csv
2222
- cat fixture/files/raw.1.json|jsoncsv -A|mkexcel > fixture/files/tmp.output.1.csv
2323
- cat fixture/files/raw.1.json|jsoncsv --array|mkexcel > fixture/files/tmp.output.1.csv
24+
- echo '{"a":{}}'|mkexcel -t xls > fixture/files/tmp.output.dict.xls
2425
after_success:
2526
- coveralls
2627
notifications:

jsoncsv/dumptool.py

+13-10
Original file line numberDiff line numberDiff line change
@@ -95,16 +95,16 @@ def write_headers(self):
9595
self.csv_writer.writeheader()
9696

9797
def write_obj(self, obj):
98-
self.csv_writer.writerow(self.patch_obj(obj))
98+
patched_obj = {
99+
key: self.patch_value(value)
100+
for key, value in obj.items()
101+
}
102+
self.csv_writer.writerow(patched_obj)
99103

100-
def patch_obj(self, obj):
101-
new_obj = {}
102-
for key, value in obj.items():
103-
if value in [None, {}, []]:
104-
value = ""
105-
106-
new_obj[key] = value
107-
return new_obj
104+
def patch_value(self, value):
105+
if value in (None, {}, []):
106+
return ""
107+
return value
108108

109109

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

129129
for head in self._headers:
130130
value = obj.get(head)
131+
# patch
132+
if value in ({},):
133+
value = "{}"
131134
self.ws.write(self.row, self.cloumn, value)
132135
self.cloumn += 1
133136

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

139142

140143
def dump_excel(fin, fout, klass, **kwargs):
141-
if not issubclass(klass, DumpExcel):
144+
if not isinstance(klass, type) or not issubclass(klass, DumpExcel):
142145
raise ValueError("unknow dumpexcel type")
143146

144147
dump = klass(fin, fout, **kwargs)

setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
setup(
1414
name='jsoncsv',
15-
version='2.2.4',
15+
version='2.2.5',
1616
url='https://github.com/alingse/jsoncsv',
1717
description='A command tool easily convert json file to csv or xlsx.',
1818
long_description=readme,

tests/test_dumptool.py

+13
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,16 @@ def test_dump_xls_with_non_ascii(self):
7070

7171
fin.close()
7272
fout.close()
73+
74+
def test_dump_xls_with_dict(self):
75+
fin = io.StringIO(u'{"a": {}}\n')
76+
fout = io.BytesIO()
77+
78+
dump_excel(fin, fout, DumpXLS)
79+
80+
fin.close()
81+
fout.close()
82+
83+
def test_dump_excel_with_error(self):
84+
with self.assertRaises(ValueError):
85+
dump_excel(None, None, None)

0 commit comments

Comments
 (0)