首页 > 解决方案 > 如何将python数据帧转换为JSON

问题描述

我在databricks环境中使用pyspark,我有一个如下数据框:

display(TestDF)

Count          Value
10             Blue
5              Green
21             Red

如何将 DF 转换为 JSON 格式,如下所示:

{"Blue":10,"Green":5,"Red":21}

我在下面尝试过,但是 JSON 的格式并不像上面那样正确

TestDF = TestDF.tojson()

{"count":10,"value":"Blue"}
{"count":5,"value":"Green"}
{"count":21,"value":"Red"}

谢谢。

标签: pythonjsondataframeapache-sparkpyspark

解决方案


我们可以使用map_from_arraysfromSpark-2.4+collect_listoncount,value列。

#if count type is not int then cast to array<int>
df.agg(to_json(map_from_arrays(collect_list(col("Value")),collect_list(col("Count")).cast("array<int>"))).alias("json")).\
show(10,False)

#if count type int then no need to casting
df.agg(to_json(map_from_arrays(collect_list(col("Value")),collect_list(col("Count")).cast("array<int>"))).alias("json")).\
show(10,False)
#+------------------------------+
#|json                          |
#+------------------------------+
#|{"Blue":10,"Green":5,"Red":21}|
#+------------------------------+

#get as string
df.agg(to_json(map_from_arrays(collect_list(col("Value")),collect_list(col("Count")).cast("array<int>"))).alias("json")).collect()[0][0]
#or
df.agg(to_json(map_from_arrays(collect_list(col("Value")),collect_list(col("Count")).cast("array<int>"))).alias("json")).collect()[0]['json']
#{"Blue":10,"Green":5,"Red":21}

推荐阅读