Skip to main content
 首页 » 编程设计

python之如何在 Python 中使用 Apache Beam 读取和操作 Json 文件

2024年09月03日35artech

我有一个 JSON 格式的 .txt 文件。我想阅读、操作和重组文件(更改字段名称...) 我如何使用 Apache Beam 在 Python 中执行此操作?

请您参考如下方法:

为了能够在 Python 上使用 Apache Beam 读取 Json 文件,您可以制作自定义编码器:

CF:https://beam.apache.org/documentation/programming-guide/#specifying-coders

class JsonCoder(object): 
"""A JSON coder interpreting each line as a JSON string.""" 
 
def encode(self, x): 
    return json.dumps(x) 
 
def decode(self, x): 
    return json.loads(x) 

然后你必须在读取或写入数据时指定它,例如:

lines = p | 'read_data' >> ReadFromText(known_args.input, coder=JsonCoder()) 

祝好,工作顺利;)