首页 > 解决方案 > 在 Spark 中推断 json 数据方案的一种方法

问题描述

假设我有带有 column 的数据框data。在本专栏中,我有一个内部带有 json 的字符串。诀窍是 json 并不总是完整的,某些行中可能缺少某些属性。

请参阅下面的示例以了解清楚

column_name_placeholder | data
foo                      {"attr1":1}
foo                      {"attr2":2}
bar                      {"attr0":"str"}
bar                      {"attr3":"po"}

我正在寻找的是一种为“column_name_placeholder”中的每个键推断完整 json 模式的方法

所以答案是这样的

foo
{
"attr1":int,
"attr2":int
}
bar
{
"attr0":string,
"attr3":string
}

我成像的唯一方法是下降到 RDD 级别并在 map 阶段使用某种 3rd 方库推断模式,然后在 reduce 阶段再次将该模式与一些 3rd 方库合并

我错过了一些火花*魔法吗?

标签: apache-sparkpyspark

解决方案


您可以转换为 RDD 并使用再次读取spark.read.json并让它推断架构。

示例column_name_placeholder = bar

spark.read.json(
    df.filter("column_name_placeholder = 'bar'").rdd.map(lambda row: row.data)
).printSchema()

#root
# |-- attr0: string (nullable = true)
# |-- attr3: string (nullable = true)

推荐阅读