【发布时间】:2014-04-18 10:10:51
【问题描述】:
有没有办法将 JSON 字符串转换为 Avro 而无需 Python 中的模式定义?还是只有 Java 才能处理?
【问题讨论】:
有没有办法将 JSON 字符串转换为 Avro 而无需 Python 中的模式定义?还是只有 Java 才能处理?
【问题讨论】:
我最近遇到了同样的问题,我最终开发了一个 python 包,它可以采用任何 python 数据结构,包括解析的 JSON,并将其存储在 Avro 中,而不需要专用的架构。
我为 python 3 测试了它。
您可以将其安装为pip3 install rec-avro 或查看代码和文档https://github.com/bmizhen/rec-avro
用法示例:
from fastavro import writer, reader, schema
from rec_avro import to_rec_avro_destructive, from_rec_avro_destructive, rec_avro_schema
def json_objects():
return [{'a': 'a'}, {'b':'b'}]
# For efficiency, to_rec_avro_destructive() destroys rec, and reuses it's
# data structures to construct avro_objects
avro_objects = (to_rec_avro_destructive(rec) for rec in json_objects())
# store records in avro
with open('json_in_avro.avro', 'wb') as f_out:
writer(f_out, schema.parse_schema(rec_avro_schema()), avro_objects)
#load records from avro
with open('json_in_avro.avro', 'rb') as f_in:
# For efficiency, from_rec_avro_destructive(rec) destroys rec, and
# reuses it's data structures to construct it's output
loaded_json = [from_rec_avro_destructive(rec) for rec in reader(f_in)]
assert loaded_json == json_objects()
要将 JSON 字符串转换为 json 对象,请使用 json.loads('{"a":"b"}')
【讨论】:
这应该会有所帮助:
b = BytesIO(b'some message')
reader = DataFileReader(b, DatumReader())
有关更多信息,请查看此Avro Python Guide。
【讨论】:
Apache Avro™ 1.7.6 Getting Started (Python):
import avro.schema
avro.schema.parse(json_schema_string)
【讨论】: