【问题标题】:How to convert JSON string to Avro in Python?如何在 Python 中将 JSON 字符串转换为 Avro?
【发布时间】:2014-04-18 10:10:51
【问题描述】:

有没有办法将 JSON 字符串转换为 Avro 而无需 Python 中的模式定义?还是只有 Java 才能处理?

【问题讨论】:

    标签: python avro


    【解决方案1】:

    我最近遇到了同样的问题,我最终开发了一个 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"}')

    【讨论】:

      【解决方案2】:

      这应该会有所帮助:

      b = BytesIO(b'some message')
      reader = DataFileReader(b, DatumReader())
      

      有关更多信息,请查看此Avro Python Guide

      【讨论】:

        【解决方案3】:

        Apache Avro™ 1.7.6 Getting Started (Python):

        import avro.schema
        avro.schema.parse(json_schema_string)
        

        【讨论】:

        • 这会解析一个 avro 架构,而不是一个序列化的 avro 文档。
        猜你喜欢
        • 1970-01-01
        • 2017-08-11
        • 2023-03-20
        • 2016-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多