我无法理解为什么在使用 StructType() 和 MapType() 更改以下代码中的 json 列时获取 null
data = [(1, '''{"a": '1'}''')]
df = spark.createDataFrame(data, ("key", "value"))
df.show()
print()
#below lien changes the data of value column to maptype
df1=df.withColumn('data',from_json(df.value,MapType(StringType(),StringType())))
df1.show()
#below line does not changes the data of value column into maptpe
schema = StructType([StructField("a", MapType(StringType(),StringType()))])
df2=df.withColumn('data',from_json(df.value, schema))
df2.show()
# df.withColumn('data',from_json(df.value,MapType(StringType(),StringType()))) produces output
+---+----------+--------+
|key| value| data|
+---+----------+--------+
| 1|{"a": '1'}|{a -> 1}|
+---+----------+--------+
#df2=df.withColumn('data',from_json(df.value, schema)) produces output
+---+----------+------+
|key| value| data|
+---+----------+------+
| 1|{"a": '1'}|{null}|
+---+----------+------+
您的第一个改变是:
你的第二个改变是:
虽然这些行看起来很相似,但模式却不同:
T.MapType(T.StringType(), T.StringType())
T.StructType([T.StructField("a", T.MapType(T.StringType(), T.StringType()))])
第一个模式是一个简单的映射,而第二个模式是包含映射的结构。这种差异就是第二种方法无法按预期工作的原因。您的第二个模式将匹配如下 json 模式:
为了达到预期的结果,您应该使用:
这将给你输出:
笔记
我使用了以下导入: