@@ -188,7 +188,7 @@ def assure_no_file_exists(path):
188
188
os .unlink (path )
189
189
190
190
191
- def save_json (filename , data , indent = 4 , sort_keys = True , pretty = False ):
191
+ def save_json (filename , data , indent = 2 , sort_keys = True , pretty = False ):
192
192
"""Save data to a json file
193
193
194
194
Parameters
@@ -203,11 +203,25 @@ def save_json(filename, data, indent=4, sort_keys=True, pretty=False):
203
203
204
204
"""
205
205
assure_no_file_exists (filename )
206
+ dumps_kw = dict (sort_keys = sort_keys , indent = indent )
207
+ j = None
208
+ if pretty :
209
+ try :
210
+ j = json_dumps_pretty (data , ** dumps_kw )
211
+ except AssertionError as exc :
212
+ pretty = False
213
+ lgr .warning (
214
+ "Prettyfication of .json failed (%s). "
215
+ "Original .json will be kept as is. Please share (if you "
216
+ "could) "
217
+ "that file (%s) with HeuDiConv developers"
218
+ % (str (exc ), filename )
219
+ )
220
+ if not pretty :
221
+ j = _canonical_dumps (data , ** dumps_kw )
222
+ assert j is not None # one way or another it should have been set to a str
206
223
with open (filename , 'w' ) as fp :
207
- fp .write (
208
- (json_dumps_pretty if pretty else _canonical_dumps )(
209
- data , sort_keys = sort_keys , indent = indent )
210
- )
224
+ fp .write (j )
211
225
212
226
213
227
def json_dumps_pretty (j , indent = 2 , sort_keys = True ):
@@ -252,25 +266,9 @@ def json_dumps_pretty(j, indent=2, sort_keys=True):
252
266
def treat_infofile (filename ):
253
267
"""Tune up generated .json file (slim down, pretty-print for humans).
254
268
"""
255
- with open (filename ) as f :
256
- j = json .load (f )
257
-
269
+ j = load_json (filename )
258
270
j_slim = slim_down_info (j )
259
- dumps_kw = dict (indent = 2 , sort_keys = True )
260
- try :
261
- j_pretty = json_dumps_pretty (j_slim , ** dumps_kw )
262
- except AssertionError as exc :
263
- lgr .warning (
264
- "Prettyfication of .json failed (%s). "
265
- "Original .json will be kept as is. Please share (if you could) "
266
- "that file (%s) with HeuDiConv developers"
267
- % (str (exc ), filename )
268
- )
269
- j_pretty = json .dumps (j_slim , ** dumps_kw )
270
-
271
- set_readonly (filename , False )
272
- with open (filename , 'wt' ) as fp :
273
- fp .write (j_pretty )
271
+ save_json (filename , j_slim , sort_keys = True , pretty = True )
274
272
set_readonly (filename )
275
273
276
274
0 commit comments