首页 >后端开发 >Python教程 >无法分解 Spark 数据框中的嵌套 JSON

无法分解 Spark 数据框中的嵌套 JSON

WBOY
WBOY转载
2024-02-11 10:51:03455浏览

无法分解 Spark 数据框中的嵌套 JSON

问题内容

我是 spark 新手。我试图展平数据框,但未能通过“爆炸”做到这一点。

原始数据框架构如下:

id|approvaljson
1|[{"approvertype":"1st line manager","status":"approved"},{"approvertype":"2nd line manager","status":"approved"}]
2|[{"approvertype":"1st line manager","status":"approved"},{"approvertype":"2nd line manager","status":"rejected"}]

我需要将其转换为以下架构?

id|approvaltype|status
1|1st line manager|approved
1|2nd line manager|approved
2|1st line manager|approved
2|2nd line manager|rejected

我已经尝试过

df_exploded = df.withcolumn("approvaljson", explode("approvaljson"))

但是我得到了错误:

Cannot resolve "explode(ApprovalJSON)" due to data type mismatch:
parameter 1 requires ("ARRAY" or "MAP") type, however, "ApprovalJSON"
is of "STRING" type.;

正确答案


首先将类似 json 的字符串解析为结构数组,然后使用 inline 将数组分解为行和列

df1 = df.withcolumn("approvaljson", f.from_json("approvaljson", schema="array<struct<approvertype string, status string>>"))
df1 = df1.select("id", f.inline('approvaljson'))

结果

df1.show()

+---+----------------+--------+
| ID|    ApproverType|  Status|
+---+----------------+--------+
|  1|1st Line Manager|Approved|
|  1|2nd Line Manager|Approved|
|  2|1st Line Manager|Approved|
|  2|2nd Line Manager|Rejected|
+---+----------------+--------+

以上是无法分解 Spark 数据框中的嵌套 JSON的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除