| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | """ |
| 8 | Type-safe data interchange for Python data classes. |
| 9 | |
| 10 | :see: https://github.com/hunyadi/strong_typing |
| 11 | """ |
| 12 | |
| 13 | import inspect |
| 14 | import json |
| 15 | import sys |
| 16 | from types import ModuleType |
| 17 | from typing import Any, Optional, TextIO, TypeVar |
| 18 | |
| 19 | from .core import JsonType |
| 20 | from .deserializer import create_deserializer |
| 21 | from .inspection import TypeLike |
| 22 | from .serializer import create_serializer |
| 23 | |
| 24 | T = TypeVar("T") |
| 25 | |
| 26 | |
| 27 | def object_to_json(obj: Any) -> JsonType: |
| 28 | """ |
| 29 | Converts a Python object to a representation that can be exported to JSON. |
| 30 | |
| 31 | * Fundamental types (e.g. numeric types) are written as is. |
| 32 | * Date and time types are serialized in the ISO 8601 format with time zone. |
| 33 | * A byte array is written as a string with Base64 encoding. |
| 34 | * UUIDs are written as a UUID string. |
| 35 | * Enumerations are written as their value. |
| 36 | * Containers (e.g. `list`, `dict`, `set`, `tuple`) are exported recursively. |
| 37 | * Objects with properties (including data class types) are converted to a dictionaries of key-value pairs. |
| 38 | """ |
| 39 | |
| 40 | typ: type = type(obj) |
| 41 | generator = create_serializer(typ) |
| 42 | return generator.generate(obj) |
| 43 | |
| 44 | |
| 45 | def json_to_object( |
| 46 | typ: TypeLike, data: JsonType, *, context: Optional[ModuleType] = None |
| 47 | ) -> object: |
| 48 | """ |
| 49 | Creates an object from a representation that has been de-serialized from JSON. |
| 50 | |
| 51 | When de-serializing a JSON object into a Python object, the following transformations are applied: |
| 52 | |
| 53 | * Fundamental types are parsed as `bool`, `int`, `float` or `str`. |
| 54 | * Date and time types are parsed from the ISO 8601 format with time zone into the corresponding Python type |
| 55 | `datetime`, `date` or `time` |
| 56 | * A byte array is read from a string with Base64 encoding into a `bytes` instance. |
| 57 | * UUIDs are extracted from a UUID string into a `uuid.UUID` instance. |
| 58 | * Enumerations are instantiated with a lookup on enumeration value. |
| 59 | * Containers (e.g. `list`, `dict`, `set`, `tuple`) are parsed recursively. |
| 60 | * Complex objects with properties (including data class types) are populated from dictionaries of key-value pairs |
| 61 | using reflection (enumerating type annotations). |
| 62 | |
| 63 | :raises TypeError: A de-serializing engine cannot be constructed for the input type. |
| 64 | :raises JsonKeyError: Deserialization for a class or union type has failed because a matching member was not found. |
| 65 | :raises JsonTypeError: Deserialization for data has failed due to a type mismatch. |
| 66 | """ |
| 67 | |
| 68 | # use caller context for evaluating types if no context is supplied |
| 69 | if context is None: |
| 70 | this_frame = inspect.currentframe() |
| 71 | if this_frame is not None: |
| 72 | caller_frame = this_frame.f_back |
| 73 | del this_frame |
| 74 | |
| 75 | if caller_frame is not None: |
| 76 | try: |
| 77 | context = sys.modules[caller_frame.f_globals["__name__"]] |
| 78 | finally: |
| 79 | del caller_frame |
| 80 | |
| 81 | parser = create_deserializer(typ, context) |
| 82 | return parser.parse(data) |
| 83 | |
| 84 | |
| 85 | def json_dump_string(json_object: JsonType) -> str: |
| 86 | "Dump an object as a JSON string with a compact representation." |
| 87 | |
| 88 | return json.dumps( |
| 89 | json_object, ensure_ascii=False, check_circular=False, separators=(",", ":") |
| 90 | ) |
| 91 | |
| 92 | |
| 93 | def json_dump(json_object: JsonType, file: TextIO) -> None: |
| 94 | json.dump( |
| 95 | json_object, |
| 96 | file, |
| 97 | ensure_ascii=False, |
| 98 | check_circular=False, |
| 99 | separators=(",", ":"), |
| 100 | ) |
| 101 | file.write("\n") |