@@ -537,7 +537,7 @@ def _save_content(content, path, file_type, keep_backup=True):
537
537
if file_type == 'json' :
538
538
with open (path , 'w' ) as the_file :
539
539
content = json_dumps (content )
540
- the_file .write (content )
540
+ the_file .write (content ) # type: ignore
541
541
elif file_type in {'yaml' , 'yml' }:
542
542
try :
543
543
import yaml
@@ -557,7 +557,7 @@ def _save_content(content, path, file_type, keep_backup=True):
557
557
content = pickle_dump (content , file_obj = the_file )
558
558
elif file_type in {'csv' , 'tsv' }:
559
559
try :
560
- import clevercsv
560
+ import clevercsv # type: ignore
561
561
dict_writer = clevercsv .DictWriter
562
562
except ImportError : # pragma: no cover.
563
563
import csv
@@ -642,7 +642,13 @@ def object_hook(self, obj):
642
642
return obj
643
643
644
644
645
- def json_dumps (item , default_mapping = None , force_use_builtin_json : bool = False , ** kwargs ):
645
+ def json_dumps (
646
+ item ,
647
+ default_mapping = None ,
648
+ force_use_builtin_json : bool = False ,
649
+ return_bytes : bool = False ,
650
+ ** kwargs ,
651
+ ) -> str | bytes :
646
652
"""
647
653
Dump json with extra details that are not normally json serializable
648
654
@@ -655,22 +661,29 @@ def json_dumps(item, default_mapping=None, force_use_builtin_json: bool=False, *
655
661
"""
656
662
if orjson and not force_use_builtin_json :
657
663
indent = kwargs .pop ('indent' , None )
664
+ kwargs ['option' ] = orjson .OPT_NON_STR_KEYS | orjson .OPT_SERIALIZE_NUMPY
658
665
if indent :
659
- kwargs ['option' ] = orjson .OPT_INDENT_2
666
+ kwargs ['option' ] | = orjson .OPT_INDENT_2
660
667
if 'sort_keys' in kwargs :
661
668
raise TypeError (
662
669
"orjson does not accept the sort_keys parameter. "
663
670
"If you need to pass sort_keys, set force_use_builtin_json=True "
664
671
"to use Python's built-in json library instead of orjson." )
665
- return orjson .dumps (
672
+ result = orjson .dumps (
666
673
item ,
667
674
default = json_convertor_default (default_mapping = default_mapping ),
668
- ** kwargs ).decode (encoding = 'utf-8' )
675
+ ** kwargs )
676
+ if return_bytes :
677
+ return result
678
+ return result .decode (encoding = 'utf-8' )
669
679
else :
670
- return json .dumps (
680
+ result = json .dumps (
671
681
item ,
672
682
default = json_convertor_default (default_mapping = default_mapping ),
673
683
** kwargs )
684
+ if return_bytes :
685
+ return result .encode (encoding = 'utf-8' )
686
+ return result
674
687
675
688
676
689
json_loads = partial (json .loads , cls = JSONDecoder )
0 commit comments