Scala spark将数据框中的一组列聚合为JSON字符串

时间:2020-02-20 07:58:08

标签: scala apache-spark

给出一个数据框,

+-----------------------------+
| id|  name| payable| strategy|
+-----------------------------+
|  0|   Joe|     100|     st-1|
|  1|   Tom|     200|     st-2|
|  2|  John|     300|     st-1|
+-----------------------------+

将每一行转换为如下所示的JSON字符串的最有效方法是什么,

{
  "payload": {
     "name": "Joe",
     "payments": [
         {
            "strategy": "st-1",
            "payable": 100
         }
     ]
  }
}

当前,我有UDF来手动对提供的列进行字符串化,但是我想知道是否有更好的方法来实现这一点。到目前为止,to_json方法是我发现的最佳替代方法,但是只需要输入一列即可。

1 个答案:

答案 0 :(得分:3)

使用to_json()是正确的方法,但是内容需要适当地以struct的形式传递:

val df = Seq((0,"Joe",100,"st-1"), (1,"Tom",200,"st-2")).toDF("id","name","payable","strategy")

val result = df.select(
  to_json(struct(
    struct($"name",
      array(struct($"strategy",$"payable")) as "payments"
    ) as "payload")
  ) as "jsonValue"
 )

result.show(false)
+-------------------------------------------------------------------------+
|jsonValue                                                                |
+-------------------------------------------------------------------------+
|{"payload":{"name":"Joe","payments":[{"strategy":"st-1","payable":100}]}}|
|{"payload":{"name":"Tom","payments":[{"strategy":"st-2","payable":200}]}}|
+-------------------------------------------------------------------------+