从pysparkDataframe解析json字符串

b0zn9rqh  于 2021-07-09  发布在  Spark
关注(0)|答案(1)|浏览(339)

我有一个嵌套的json dict,需要将其转换为spark dataframe。这个json dict存在于dataframe列中。我一直在尝试使用“from\ json”和“get\ json\ object”解析dataframe列中的dict,但无法读取数据。以下是我试图读取的源数据的最小片段:

{"value": "\u0000\u0000\u0000\u0000/{\"context\":\"data\"}"}

我需要提取嵌套的dict值。我使用下面的代码清理数据并将其读入Dataframe

from pyspark.sql.functions import *
from pyspark.sql.types import *
input_path = '/FileStore/tables/enrl/context2.json      #path for the above file
schema1 = StructType([StructField("context",StringType(),True)]) #Schema I'm providing
raw_df = spark.read.json(input_path)
cleansed_df = raw_df.withColumn("cleansed_value",regexp_replace(raw_df.value,'/','')).select('cleansed_value') #Removed extra '/' in the data

cleansed_df.select(from_json('cleansed_value',schema=schema1)).show(1, truncate=False)

每次运行上述代码时,我都会得到一个空的Dataframe。请帮忙。
尝试了以下内容,但没有成功:pyspark:从字符串类型的列中读取嵌套的json并创建列
还尝试将其写入json文件并读取。它也不起作用:在pyspark中读取嵌套的json文件

yhqotfr8

yhqotfr81#

空字符 \u0000 影响json的解析。您也可以替换它们:

df = spark.read.json('path')

df2 = df.withColumn(
    'cleansed_value', 
    F.regexp_replace('value','[\u0000/]','')
).withColumn(
    'parsed', 
    F.from_json('cleansed_value','context string')
)

df2.show(20,0)
+-----------------------+------------------+------+
|value                  |cleansed_value    |parsed|
+-----------------------+------------------+------+
|/{"context":"data"}|{"context":"data"}|[data]|
+-----------------------+------------------+------+

相关问题