如何在 pyspark 中解析和转换来自 Spark 数据帧行的 json 字符串?
我正在寻找如何解析的帮助:
- json 字符串到 json 结构
output 1
- 将 json 字符串转换为 a、b 和 id 列
output 2
背景:我通过 API json 字符串获取大量行(jstr1
, jstr2
, ...),这些被保存到 Sparkdf
。我可以单独读取每一行的模式,但这不是解决方案,因为它非常慢,因为模式有大量行。每个jstr
具有相同的架构,列/键 a 和 b 保持相同,只是id
并且列中的值发生变化。
编辑:使用 MapType 模式的 blackbishop 解决方案就像一个魅力schema = "map<string, array<struct<a:int,b:int>>>"
问题延伸至:如何从 pyspark 中的 Spark 数据帧行转换具有多个键的 JSON 字符串?
from pyspark.sql import Row
jstr1 = '{"id_1": [{"a": 1, "b": 2}, {"a": 3, "b": 4}]}'
jstr2 = '{"id_2": [{"a": 5, "b": 6}, {"a": 7, "b": 8}]}'
df = sqlContext.createDataFrame([Row(json=jstr1),Row(json=jstr2)])
schema = F.schema_of_json(df.select(F.col("json")).take(1)[0].json)
df2 = df.withColumn('json', F.from_json(F.col('json'), schema))
df2.show()
电流输出:
+--------------------+
| json|
+--------------------+
|[[[1, 2], [3, 4]]] |
| []|
+--------------------+
所需输出1:
+--------------------+-------+
| json | id |
+--------------------+-------+
|[[[1, 2], [3, 4]]] | id_1 |
|[[[5, 6], [7, 8]]] | id_2 |
+--------------------+-------+
所需输出2:
+---------+----------+-------+
| a | b | id |
+--------------------+-------+
| 1 | 2 | id_1 |
| 3 | 4 | id_1 |
| 5 | 6 | id_2 |
| 7 | 8 | id_2 |
+---------+----------+-------+