【问题标题】:Spark Dataframe with JSON as String in it, to be cast as nested json将 JSON 作为字符串的 Spark Dataframe,转换为嵌套的 json
【发布时间】:2018-09-25 17:23:35
【问题描述】:

我在 Spark 中处理 JSON 数据时遇到问题。

DataFrame 有一列包含字符串格式的 JSON。

DF 架构:

root
 |-- id: string (nullable = true)
 |-- jsonString: string (nullable = true)

示例 jsonString:"{\"sample\":\"value\"}";

我想将此 jsonString 转换为嵌套的 JSON 对象。这样可以读取和遍历 JSON 数据。

我正在寻找的目标DF结构如下。

root
 |-- id: string (nullable = true)
 |-- json: struct (nullable = true)
 |   |-- sample: string (nullable = true)

感谢任何帮助。

【问题讨论】:

    标签: json apache-spark dataframe


    【解决方案1】:

    您可以使用to_json 函数来转换jsonString。为此,您需要创建一个架构

    //dummy data 
    val data = Seq(
      ("a", "{\"sample\":\"value1\"}"),
      ("b", "{\"sample\":\"value2\"}"),
      ("c", "{\"sample\":\"value3\"}")
    ).toDF("id", "jsonString")
    
    //create schema for jsonString 
    
    val schema = StructType(StructField("sample", StringType, true):: Nil)
    
    //create new column with from_json using schema 
    data.withColumn("newCol", from_json($"jsonString", schema))
    

    输出架构:

    root
     |-- id: string (nullable = true)
     |-- jsonString: string (nullable = true)
     |-- newCol: struct (nullable = true)
     |    |-- sample: string (nullable = true)
    

    输出:

    +---+-------------------+--------+
    |id |jsonString         |newCol  |
    +---+-------------------+--------+
    |a  |{"sample":"value1"}|[value1]|
    |b  |{"sample":"value2"}|[value2]|
    |c  |{"sample":"value3"}|[value3]|
    +---+-------------------+--------+
    

    希望这会有所帮助!

    【讨论】:

    • 到 OP,然后您可以根据需要删除原点 jsonString 列。
    • 感谢您的帮助。但我有一种情况,我无法创建 Schema。
    猜你喜欢
    • 2020-09-02
    • 1970-01-01
    • 2019-09-26
    • 2021-09-14
    • 2020-02-16
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 2019-06-09
    相关资源
    最近更新 更多