在 Spark SQL 中,将 JSON 键名转换为值

In Spark SQL, transform JSON key name into value

Spark SQL 中似乎应该有一个类似于旋转的函数,但我还没有找到将 JSON 键转换为值的任何解决方案。假设我的 JSON 格式错误(我无法更改其格式):

{"A long string containing serverA": {"x": 1, "y": 2}}

如何处理到

{"server": "A", "x": 1, "y": 2}

?

我将 JSON 读入一个 sql.dataframe,然后想按上述方式处理它们:

val cs = spark.read.json("sample.json")
  .???

如果我们只想使用 spark 函数而不使用 UDF,您可以使用 from_json 将 json 解析为一个映射(我们需要指定一个模式)。然后你只需要使用 spark 函数提取信息。 一种方法如下:

val schema = MapType(
    StringType,
    StructType(Array(
        StructField("x", IntegerType),
        StructField("y", IntegerType)
    ))
)

spark.read.text("...")
    .withColumn("json", from_json('value, schema))
    .withColumn("key", map_keys('json).getItem(0))
    .withColumn("value", map_values('json).getItem(0))
    .withColumn("server",
        // Extracting the server name with a regex
        regexp_replace(regexp_extract('key, "server[^ ]*", 0), "server", ""))
    .select("server", "value.*")
    .show(false)

产生:

+------+---+---+
|server|x  |y  |
+------+---+---+
|A     |1  |2  |
+------+---+---+