【发布时间】:2021-05-28 15:40:18
【问题描述】:
我有一个 json 文件,其中包含如下所示的数据:
"Url": "https://sample.com", "Method": "POST", "Headers": [{"Key": "accesstoken", "Value": ["123"]}, {"Key": "id", "Value": ["abc"]}, {"Key": "context", "Value": ["sample"]}]
在读取 json 时,我将架构明确定义为:
schema = StructType(
[
StructField('Url', StringType(), True),
StructField('Method', StringType(), True),
StructField("Headers",ArrayType(StructType([
StructField('Key', StringType(), True),
StructField("Value",ArrayType(StringType()),True),
]),True),True)
]
)
目标是将键值数据作为列而不是行来读取。
| Url | Method | accesstoken | id | context |
|---|---|---|---|---|
| https://sample.com | POST | 123 | abc | sample |
分解“标题”列只会将其转换为多行。数据的另一个问题是,我的键值对值存储在 2 个单独的对中,而不是文字键值对(例如“accesstoken”:“123”)!
我尝试遍历这些值以首先创建地图,但我无法遍历“标题”列。
df_map = df.withColumn('map', to_json(array(*[create_map(element.Key, element.Value) for element in df.Headers])))
我还尝试将“标题”列读取为 MapType(StringType, ArrayType(StringType)),但它无法读取该值。当我这样做时它显示为 null。
有没有办法做到这一点?我是否必须以纯文本形式读取数据并预处理数据而不是数据框?
【问题讨论】:
标签: apache-spark pyspark apache-spark-sql key-value