|
| 1 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +from abc import ABC, abstractmethod |
| 5 | +from typing import Any, Union |
| 6 | +from types import SimpleNamespace |
| 7 | + |
| 8 | + |
| 9 | +""" |
| 10 | +Azure Functions JSON utilities. |
| 11 | +This module provides a JSON interface that can be used to serialize and |
| 12 | +deserialize objects to and from JSON format. It supports both the `orjson` |
| 13 | +and the standard `json` libraries, falling back to the standard library |
| 14 | +if `orjson` is not available (installed). |
| 15 | +""" |
| 16 | + |
| 17 | + |
| 18 | +try: |
| 19 | + import orjson as _orjson |
| 20 | +except ImportError: |
| 21 | + _orjson = None |
| 22 | + |
| 23 | +# Standard library is always present |
| 24 | +import json as _std_json |
| 25 | + |
| 26 | + |
| 27 | +class JsonInterface(ABC): |
| 28 | + @abstractmethod |
| 29 | + def dumps(self, obj: Any) -> str: |
| 30 | + pass |
| 31 | + |
| 32 | + @abstractmethod |
| 33 | + def loads(self, s: Union[str, bytes, bytearray]) -> Any: |
| 34 | + pass |
| 35 | + |
| 36 | + |
| 37 | +class OrJsonAdapter(JsonInterface): |
| 38 | + def __init__(self): |
| 39 | + assert _orjson is not None |
| 40 | + self.orjson = _orjson |
| 41 | + |
| 42 | + def dumps(self, obj: Any) -> str: |
| 43 | + # orjson.dumps returns bytes, decode to str |
| 44 | + return self.orjson.dumps(obj).decode("utf-8") |
| 45 | + |
| 46 | + def loads(self, s: Union[str, bytes, bytearray]) -> Any: |
| 47 | + return self.orjson.loads(s) |
| 48 | + |
| 49 | + |
| 50 | +class StdJsonAdapter(JsonInterface): |
| 51 | + def __init__(self): |
| 52 | + self.json = _std_json |
| 53 | + |
| 54 | + def dumps(self, obj: Any) -> str: |
| 55 | + return self.json.dumps(obj) |
| 56 | + |
| 57 | + def loads(self, s: Union[str, bytes, bytearray]) -> Any: |
| 58 | + return self.json.loads(s) |
| 59 | + |
| 60 | + |
| 61 | +if _orjson is not None: |
| 62 | + json_impl = OrJsonAdapter() |
| 63 | +else: |
| 64 | + json_impl = StdJsonAdapter() |
| 65 | + |
| 66 | + |
| 67 | +def dumps(obj: Any) -> str: |
| 68 | + return json_impl.dumps(obj) |
| 69 | + |
| 70 | + |
| 71 | +def loads(s: Union[str, bytes, bytearray]) -> Any: |
| 72 | + return json_impl.loads(s) |
| 73 | + |
| 74 | + |
| 75 | +json = SimpleNamespace( |
| 76 | + dumps=dumps, |
| 77 | + loads=loads |
| 78 | +) |
0 commit comments