arrays - 从数据框中删除空数组字段,同时将其转换为 JSON
问题描述
有没有什么方法可以通过不使用那些为空的字段从 spark 数据帧创建 json:
假设我有一个数据框:
+-------+----------------+
| name| hit_songs|
+-------+----------------+
|beatles|[help, hey jude]|
| romeo| [eres mia]|
| juliet| null |
+-------+----------------+
我想把它转换成一个json,比如:
[{
name: "beatles",
hit_songs: [help, hey jude]
},
{
name: "romeo",
hit_songs: [eres mia]
},
{
name: "juliet"
}
]
我不希望 json_object 中的 hit_songs 字段的值为 null
解决方案
在这种情况下使用to_json
函数。
df=spark.createDataFrame([("beatles",["help","hey juude"]),("romeo",["eres mia"]),("juliet",None)],["name","hit_songs"])
from pyspark.sql.functions import *
df.groupBy(lit(1)).\
agg(collect_list(to_json(struct('name','hit_songs'))).alias("json")).\
drop("1").\
show(10,False)
#+-------------------------------------------------------------------------------------------------------------------+
#|json |
#+-------------------------------------------------------------------------------------------------------------------+
#|[{"name":"beatles","hit_songs":["help","hey juude"]}, {"name":"romeo","hit_songs":["eres mia"]}, {"name":"juliet"}]|
#+-------------------------------------------------------------------------------------------------------------------+
#using toJSON function.
df.groupBy(lit(1)).\
agg(collect_list(struct('name','hit_songs')).alias("json")).\
drop("1").\
toJSON().\
collect()
#[u'{"json":[{"name":"beatles","hit_songs":["help","hey juude"]},{"name":"romeo","hit_songs":["eres mia"]},{"name":"juliet"}]}']
推荐阅读
- amazon-web-services - AWS:如果只有弹性 IP 与目标组中的实例相关联,则文件从 EC2 保存到 S3。其他文件不写
- javascript - 如何在请求后捕获错误(消息)
- javascript - D3.min 不返回最小值
- python - 估计拍摄图像的高度
- python - 无法解析文件 saved_model.pb:解析消息时出错
- flutter - 颤振列表视图构建器显示所选名称的 id
- python - sqlite3 未被识别为外部或内部命令
- javascript - 在范围滑块中显示两个值
- javascript - Expo React Native 与 Type Script 编写的包
- javascript - 类似于选项卡的功能,但附加到另一个 div 的场景