从 Pyspark 数据帧解析 JSON 字符串

时间:2021-04-01 09:07:11

标签: python json apache-spark pyspark apache-spark-sql

我有一个嵌套的 JSON dict,我需要将其转换为 spark 数据帧。此 JSON dict 存在于数据框列中。我一直在尝试使用“from_json”和“get_json_object”解析数据帧列中的字典,但一直无法读取数据。这是我一直在尝试阅读的源数据的最小片段:

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

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

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)

每次运行上述代码时,我都会得到一个空数据帧。请帮忙。

尝试了以下内容,但没有奏效: PySpark: Read nested JSON from a String Type Column and create columns

还尝试将其写入 JSON 文件并读取它。它也不起作用: reading a nested JSON file in pyspark

1 个答案:

答案 0 :(得分:1)

空字符 \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]|
+-----------------------+------------------+------+