繁体   English   中英

在 pyspark 模式中将 json 列作为字符串打开并使用它

[英]Opening a json column as a string in pyspark schema and working with it

我有一个很大的 dataframe 我无法从中推断出架构。 我有一列可以读取,好像每个值都是 json 格式,但我不知道它的全部细节(即键和值可以变化,我不知道它可以是什么)。

我想将它作为字符串读取并使用它,但在此过程中格式会以一种奇怪的方式发生变化; 这是一个例子:

from pyspark.sql.types import *

data = [{"ID": 1, "Value": {"a":12, "b": "test"}},
        {"ID": 2, "Value": {"a":13, "b": "test2"}}
        ]
df = spark.createDataFrame(data)


#change my schema to open the column as string
schema = df.schema
j = schema.jsonValue()
j["fields"][1] = {"name": "Value", "type": "string", "nullable": True, "metadata": {}}
new_schema = StructType.fromJson(j)

df2 = spark.createDataFrame(data, schema=new_schema)
df2.show()

给我

+---+---------------+
| ID|          Value|
+---+---------------+
|  1| {a=12, b=test}|
|  2|{a=13, b=test2}|
+---+---------------+

如您所见,“值”列中的格式现在没有引号,并且使用“=”而不是“:”,我无法再正常使用它了。 如何将其转回 StructType 或 MapType?

假设这是您的输入 dataframe:

df2 = spark.createDataFrame([
    (1, "{a=12, b=test}"), (2, "{a=13, b=test2}")
], ["ID", "Value"])

从字符串列中删除{}后,您可以使用str_to_map function,如下所示:

from pyspark.sql import functions as F

df = df2.withColumn(
    "Value",
    F.regexp_replace("Value", "[{}]", "")
).withColumn(
    "Value",
    F.expr("str_to_map(Value, ', ', '=')")
)

df.printSchema()
#root
# |-- ID: long (nullable = true)
# |-- Value: map (nullable = true)
# |    |-- key: string
# |    |-- value: string (valueContainsNull = true)

df.show()
#+---+---------------------+
#|ID |Value                |
#+---+---------------------+
#|1  |{a -> 12, b -> test} |
#|2  |{a -> 13, b -> test2}|
#+---+---------------------+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM