【发布时间】:2021-06-28 06:42:17
【问题描述】:
我有一个嵌套的 JSON 字典,需要将其转换为 spark 数据框。此 JSON dict 存在于数据框列中。我一直在尝试使用“from_json”和“get_json_object”解析数据框列中存在的dict,但无法读取数据。这是我一直在尝试读取的源数据中最小的 sn-p:
{"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
【问题讨论】:
标签: python json apache-spark pyspark apache-spark-sql