如何在PySpark中将字符串转换为字典(JSON)的ArrayType


问题内容

尝试将StringType转换为JSON的ArrayType,以获取由CSV生成的数据帧。

pyspark在上使用Spark2

我正在处理的CSV文件;如下-

date,attribute2,count,attribute3
2017-09-03,'attribute1_value1',2,'[{"key":"value","key2":2},{"key":"value","key2":2},{"key":"value","key2":2}]'
2017-09-04,'attribute1_value2',2,'[{"key":"value","key2":20},{"key":"value","key2":25},{"key":"value","key2":27}]'

如上所示,它"attribute3"在文字字符串中包含一个属性,从技术上讲,它是一列字典(JSON),其精确长度为2。(这是函数的输出)

的摘录 printSchema()

attribute3: string (nullable = true)

我正在尝试将"attribute3"转换ArrayType

temp = dataframe.withColumn(
    "attribute3_modified",
    dataframe["attribute3"].cast(ArrayType())
)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() takes at least 2 arguments (1 given)

确实,ArrayType期望数据类型作为参数。我尝试使用"json",但是没有用。

所需的输出-最后,我需要转换attribute3ArrayType()普通的简单Python列表。(我正在尝试避免使用eval

如何将其转换为ArrayType,以便将其视为JSON列表?

我在这里想念什么吗?

文档没有以简单的方式解决此问题)


问题答案:

from_json与匹配attribute3列中的实际数据的架构一起使用,以将json转换为ArrayType:

原始数据框:

df.printSchema()
#root
# |-- date: string (nullable = true)
# |-- attribute2: string (nullable = true)
# |-- count: long (nullable = true)
# |-- attribute3: string (nullable = true)

from pyspark.sql.functions import from_json
from pyspark.sql.types import *

创建 模式

schema = ArrayType(
    StructType([StructField("key", StringType()), 
                StructField("key2", IntegerType())]))

用途from_json

df = df.withColumn("attribute3", from_json(df.attribute3, schema))

df.printSchema()
#root
# |-- date: string (nullable = true)
# |-- attribute2: string (nullable = true)
# |-- count: long (nullable = true)
# |-- attribute3: array (nullable = true)
# |    |-- element: struct (containsNull = true)
# |    |    |-- key: string (nullable = true)
# |    |    |-- key2: integer (nullable = true)

df.show(1, False)
#+----------+----------+-----+------------------------------------+
#|date      |attribute2|count|attribute3                          |
#+----------+----------+-----+------------------------------------+
#|2017-09-03|attribute1|2    |[[value, 2], [value, 2], [value, 2]]|
#+----------+----------+-----+------------------------------------+