|
3 | 3 | import io
|
4 | 4 | import os
|
5 | 5 | import json
|
| 6 | +import orjson |
6 | 7 | import uuid
|
7 | 8 | import logging
|
8 | 9 | import re # NOQA
|
@@ -181,7 +182,7 @@ def to_json(self, default_mapping=None, **kwargs):
|
181 | 182 | '{"type_changes": {"root": {"old_type": "A", "new_type": "B", "old_value": "obj A", "new_value": "obj B"}}}'
|
182 | 183 | """
|
183 | 184 | dic = self.to_dict(view_override=TEXT_VIEW)
|
184 |
| - return json.dumps(dic, default=json_convertor_default(default_mapping=default_mapping), **kwargs) |
| 185 | + return json_dumps(dic, default_mapping=default_mapping, **kwargs) |
185 | 186 |
|
186 | 187 | def to_dict(self, view_override=None):
|
187 | 188 | """
|
@@ -410,7 +411,7 @@ def load_path_content(path, file_type=None):
|
410 | 411 | file_type = path.split('.')[-1]
|
411 | 412 | if file_type == 'json':
|
412 | 413 | with open(path, 'r') as the_file:
|
413 |
| - content = json.load(the_file) |
| 414 | + content = json_loads(the_file.read()) |
414 | 415 | elif file_type in {'yaml', 'yml'}:
|
415 | 416 | if yaml is None: # pragma: no cover.
|
416 | 417 | raise ImportError('Pyyaml needs to be installed.') # pragma: no cover.
|
@@ -474,7 +475,8 @@ def save_content_to_path(content, path, file_type=None, keep_backup=True):
|
474 | 475 | def _save_content(content, path, file_type, keep_backup=True):
|
475 | 476 | if file_type == 'json':
|
476 | 477 | with open(path, 'w') as the_file:
|
477 |
| - content = json.dump(content, the_file) |
| 478 | + content = json_dumps(content) |
| 479 | + the_file.write(content) |
478 | 480 | elif file_type in {'yaml', 'yml'}:
|
479 | 481 | if yaml is None: # pragma: no cover.
|
480 | 482 | raise ImportError('Pyyaml needs to be installed.') # pragma: no cover.
|
@@ -504,8 +506,15 @@ def _save_content(content, path, file_type, keep_backup=True):
|
504 | 506 | return content
|
505 | 507 |
|
506 | 508 |
|
| 509 | +def _serialize_decimal(value): |
| 510 | + if value.as_tuple().exponent == 0: |
| 511 | + return int(value) |
| 512 | + else: |
| 513 | + return float(value) |
| 514 | + |
| 515 | + |
507 | 516 | JSON_CONVERTOR = {
|
508 |
| - decimal.Decimal: float, |
| 517 | + decimal.Decimal: _serialize_decimal, |
509 | 518 | ordered_set.OrderedSet: list,
|
510 | 519 | type: lambda x: x.__name__,
|
511 | 520 | bytes: lambda x: x.decode('utf-8'),
|
@@ -552,7 +561,10 @@ def json_dumps(item, default_mapping=None, **kwargs):
|
552 | 561 | but the output it makes is a byte object and Postgres couldn't directly use it without
|
553 | 562 | encoding to str. So I switched back to json.
|
554 | 563 | """
|
555 |
| - return json.dumps(item, default=json_convertor_default(default_mapping=default_mapping), **kwargs) |
| 564 | + return orjson.dumps( |
| 565 | + item, |
| 566 | + default=json_convertor_default(default_mapping=default_mapping), |
| 567 | + **kwargs).decode(encoding='utf-8') |
556 | 568 |
|
557 | 569 |
|
558 | 570 | json_loads = partial(json.loads, cls=JSONDecoder)
|
0 commit comments