首页 > 解决方案 > 在 Spark Scala 中完成 Dataframe.toJSON 时时间戳格式得到转换

问题描述

我在配置单元表中有时间戳列,它使用 spark sql 读入 Dataframe。获得数据帧后,我使用 Spark 中的 toJSON 函数将数据帧转换为 JSON 字符串。

但是时间戳格式是在将 toJSON 应用于数据帧后转换的

代码和输出如下。

scala> newDF.show(false)
+--------------------------+--------------------------+
|current_ts                  |new_ ts                   |
+--------------------------+--------------------------+
|2019-04-10 01:00:27.551022|2019-04-10 06:00:27.551022|
|2019-04-10 01:00:49.07757 |2019-04-10 06:00:49.07757 |


scala> newDF.toJSON.show(false)
+-------------------------------------------------------------------------------------------+
|value                                                                                      |
+-------------------------------------------------------------------------------------------+
|{" current_ts ":"2019-04-10T01:00:27.551-05:00","new_ ts":"2019-04-10T06:00:27.551-05:00"}|
|{" current_ts ":"2019-04-10T01:00:49.077-05:00","new_ ts":"2019-04-10T06:00:49.077-05:00"}|

不接受以上输出,我们需要将时间戳作为其显示在 Dataframe 中,而不将其转换为 String 数据类型。

我需要的输出如下

+-------------------------------------------------------------------------------------------+
|value                                                                                      |
+-------------------------------------------------------------------------------------------+
|{" current_ts ":"2019-04-10T01:00:27.551022","new_ ts":"2019-04-10T06:00:27.551022"}|
|{" current_ts ":"2019-04-10T01:00:49.07757","new_ ts":"2019-04-10T06:00:49.07757"}|

标签: jsonscaladataframeapache-sparktimestamp

解决方案


我得到了预期的输出。请看下面:

scala> val df = Seq(("2019-04-10 01:00:27.551022", "2019-04-10 06:00:27.551022"),("2019-04-10 01:00:49.07757", " 2019-04-10 06:00:49.07757").toDF("current_ts","new_ts")

输出

scala> df.toJSON.show(false)
+---------------------------------------------------------------------------------+
|value                                                                            |
+---------------------------------------------------------------------------------+
|{"current_ts":"2019-04-10 01:00:27.551022","new_ts":"2019-04-10 06:00:27.551022"}|
|{"current_ts":"2019-04-10 01:00:49.07757","new_ts":"2019-04-10 06:00:49.07757"}  |
+---------------------------------------------------------------------------------+

我正在使用 Spark 2.4。能否请您也指定版本。

谢谢。


推荐阅读