如何在 Python 中输入注释 JSON 数据?

Mil*_*rma 8 python python-3.x

我在很多代码中添加类型注释,以便其他开发人员清楚我的函数和方法的作用。我如何键入注释一个将 JSON 数据作为参数并返回 JSON 数据的函数?

(非常简化的版本)

def func(json_data):
    return json_data
Run Code Online (Sandbox Code Playgroud)

我想要做什么,但使用 JSON 而不是 int:

def add_nums(a: int, b: int) -> int:
    return a+b
Run Code Online (Sandbox Code Playgroud)

Sam*_*ath 6

Json 对象通常就像一袋物品。它可以有数字、字符串、浮点数、列表和嵌套 json 对象。如果您希望深入了解 JSON 主体的实际结构,那么以下选项 1 和 2 可以帮助您,或者您可以执行第三步。

第一个选项: 请检查此Python3 文档链接

如果您可以清楚地定义 json 正文,那么您可以使用以下示例。

from collections.abc import Sequence

ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
Run Code Online (Sandbox Code Playgroud)

第二个选项:您还可以定义自己的自定义类型类来使用,这与上面创建大量全局项目不同。

https://docs.python.org/3/library/typing.html#newtype


from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)

def get_user_name(user_id: UserId) -> str:
    ...
Run Code Online (Sandbox Code Playgroud)

第三种选择:就像上面建议的答案一样,使用一种str简单的方法。将 json 正文视为字符串,并使用 json 模块将其转换为字符串,反之亦然

第四个选项:使用库来定义类 - https://marshmallow.readthedocs.io/en/stable/

如果您正在使用 Apache Spark,那么https://github.com/ketgo/marshmallow-pyspark值得了解。