如何在Python中使用联合类型创建Avro

问题描述 投票:0回答:1

我尝试在 Python 中将 JSON 文件转换为 Avro,需要注意的是该模式具有联合类型。更具体地说,在最小的非工作示例中,JSON 文件只是

{"field1": {"int": 17} }
,而架构是
{"type": "record", "name": "ROOT", "fields": [{"name": "field1", "type": ["null","int"] }] }

我的示例被 avro-tools 正确识别(命令

java -jar avro-tools.jar fromjson --schema-file schema.avsc sample1.json > sample1.avro
生成有效的 Avro 文件)。但是,Python 库有一个问题,无法识别我的 JSON 对于我的架构有效。您可以在下面找到示例代码

import json
import avro
from avro.datafile import DataFileWriter, DataFileReader
from avro.io import DatumWriter, DatumReader

schema = """{"type": "record", "name": "ROOT", "fields": 
 [{"name": "field1", "type": ["null","int"] }] }"""

example1="""{"field1": {"int": 17} }"""

schema_parsed = avro.schema.Parse(schema)

with open('TEST.avro', 'wb') as f:
    writer = DataFileWriter(f, DatumWriter(), schema_parsed)
    writer.append(json.loads(example1))
    writer.close()

基于这篇博文;它会生成错误消息

AvroTypeException: The datum {'field1': {'int': 17}} is not an example of the schema... 

在 Python 中处理此类示例的正确方法是什么?

我使用Python 3.10.10,

pip list | grep avro
的结果是:avro-python3版本1.10.2,fastavro版本1.8.2。

python avro union-types
1个回答
0
投票

看起来 JSON 文件有两个不兼容的规范:avro-tools 使用的一个(基于 Java)和原生 Python 库使用的一个,这很混乱。

Python 库需要对具有联合类型的字段中的 JSON 文件使用更简单的语法,并将一行代码更改为

example1="""{"field1": {"int": 17} }"""
可消除错误。

© www.soinside.com 2019 - 2024. All rights reserved.