【问题标题】:How to convert JSON to Spark schema automatically?如何自动将 JSON 转换为 Spark 模式?
【发布时间】:2021-07-02 00:18:32
【问题描述】:

我有一个很大的 JSON,想在 Spark Structured Streaming 中使用。我不想手动将此 JSON 重新键入为 Spark 模式表达式。我可以自动执行一次吗?


这是我写的

from pyspark.sql import SparkSession

spark = SparkSession \
    .builder \
    .appName("Infer Schema") \
    .getOrCreate()

df = spark \
    .read \
    .option("multiline", True) \
    .json("file_examples/dataflow/row01.json")

df.printSchema()

df.show()

with open("dataflow_schema.json", "w") as fp:
    fp.write(df.schema.json())

这样好吗?

【问题讨论】:

  • 我添加了一个带有一些 kafka 注释的示例,如果这对你有用,请告诉我

标签: json apache-spark pyspark spark-structured-streaming


【解决方案1】:

你走在正确的道路上。您可以将架构保存为 json,然后再加载。请务必在使用前将其转换为json,然后再转换为StructType

import json
from pyspark.sql.types import StructType

with open("dataflow_schema.json", "r") as fp:
    json_schema_str = fp.read()
    my_schema = StructType.fromJson(json.loads(json_schema_str))

在您的结构化流式查询中,如果您有 json 列,您可以使用 from_json 方法将您的 json 转换为 struct 类型并最终转换为多个列,例如:

from pyspark.sql.functions import from_json,col

# Assume that we have a kafkaStream
kafkaStream.selectExpr("CAST(value as string)")\
           .select(from_json(col("value"),my_schema).alias("json_value"))\
           .selectExpr("json_value.*") # extract as columns

【讨论】:

  • 谢谢!我接近了,但所有解析的值似乎都是null。没有错误消息。
猜你喜欢
  • 2020-01-17
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
  • 2020-02-23
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
相关资源
最近更新 更多