【问题标题】:Python Avro writer.append doesn't work when a json string is passed as a variable.当 json 字符串作为变量传递时,Python Avro writer.append 不起作用。
【发布时间】:2016-08-17 05:59:29
【问题描述】:

Avro 架构文件:user.avsc

{"namespace": "example.avro",
 "type": "record",
 "name": "User",
 "fields": [
     {"name": "TransportProtocol", "type": "string"}
 ]
}

粘贴我的代码 sn-p 有效:-

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

schema = avro.schema.parse(open("user.avsc").read())
writer = DataFileWriter(open("users.avro", "w"), DatumWriter(), schema)
writer.append({"TransportProtocol": "udp"})
writer.close()

粘贴我的代码 sn-p 不起作用:-

dummy_json = '{"TransportProtocol": "udp"}'
schema = avro.schema.parse(open("user.avsc").read())
writer = DataFileWriter(open("users.avro", "w"), DatumWriter(), schema)
writer.append(dummy_json)
writer.close()

当我在 append 函数中传递 json 字符串时,它会输出并得到所需的 avro 输出。但是如果我将 json 字符串初始化为一个变量,然后尝试在 append 函数中传递该变量,它就不起作用并抛出一个错误:-

avro.io.AvroTypeException: The datum {"TransportProtocol": "udp"} is not an example of the schema {

有什么帮助吗?谢谢

【问题讨论】:

    标签: python avro writer


    【解决方案1】:

    我认为这可能是因为在您的第一个示例中,您实际上传递了字典 {"TransportProtocol": "udp"},而不是字符串。但在第二个中,您传递了一个字符串'{"TransportProtocol": "udp"}'

    看看这个(http://avro.apache.org/docs/1.7.6/gettingstartedpython.html):

    我们使用 DataFileWriter.append 将项目添加到我们的数据文件中。阿夫罗 记录表示为 Python dicts。

    所以基本上,你不能将字符串作为参数传递。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-19
      • 2014-06-16
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 1970-01-01
      相关资源
      最近更新 更多