python - 将 json 对象反序列化为 Faust 记录,其中 json 在键名中有连字符
问题描述
我有一个看起来像的 JSON 对象
{
"timestamp": "2020-06-24T15:32:56.775518Z",
"record-type": "data",
"operation": "load",
"partition-key-type": "primary-key",
"schema-name": "legacy",
"table-name": "test"
}
我正在尝试将记录反序列化为
class MetadataModel(faust.Record):
timestamp: str
record-type: str # does not work, hyphens in name not allowed
schema_name: str # does not work
tableName: str # does not work
我可能遗漏了一些简单的东西,但是如何从键中有连字符的 json 对象转到 python 对象。任何帮助将非常感激!
解决方案
您可以使用字段类faust.models.fields
在 JSON 中提供自定义名称。
import faust
from faust.models.fields import StringField
class MetadataModel(faust.Record):
timestamp: str
record_type: str = StringField(input_name='record-type')
operation: str
partition_key_type: str = StringField(input_name='partition-key-type')
schema_name: str = StringField(input_name='schema-name')
table_name: str = StringField(input_name='table-name')
json_bytes = b"""
{
"timestamp": "2020-06-24T15:32:56.775518Z",
"record-type": "data",
"operation": "load",
"partition-key-type": "primary-key",
"schema-name": "legacy",
"table-name": "test"
}
"""
print(MetadataModel.loads(json_bytes, default_serializer='json'))
输出:
<MetadataModel: timestamp='2020-06-24T15:32:56.775518Z', record_type='data', operation='load', partition_key_type='primary-key', schema_name='legacy', table_name='test'>
推荐阅读
- c++ - 打印类似 ASCII 的字符,并且在 char 的绘图中找不到我的错误
- javascript - 此代码的时间复杂度和排序算法类型
- javascript - 与数据列表选项进行比较时,如何忽略文本输入中的尾随空格?
- sql-server - asp.net core web api 返回 500 服务器错误
- javascript - 棋盘画布,循环并在 JS 画布中将一些棋子作为圆圈
- css - 内部带有 for 循环的 SCSS 函数不起作用
- json - 不支持“freeplay”(字符串)类型
- python - python regex:在javascript函数中搜索变量内容
- python - Python dictionary.values() 到 numpy 数组
- python - 在列表中查找术语