Forum Discussion
PySpark Notebook to process complex JSON
- Anonymous2 years ago
Hi ToddChitt ,
I tried to do some repro around your case, it is working perfectly fine.
Can you please find the code below,Sample Json:
[ { "id": "00000001-0000-0000-0000-000000000000", "positionData": { "manager": { "id": "00000002-0000-0000-0000-000000000000", "employeeNumber": "1234" } } }, { "id": "00000001-0000-0000-0000-000000000000", "positionData": { "manager": null } } ]
Sample Code:from pyspark.sql.types import StructType, StructField, StringType, ArrayType from pyspark.sql.functions import col, coalesce, lit # Define the schema for the nested objects schema = StructType([ StructField("id", StringType(), True), StructField("positionData", StructType([ StructField("manager", StructType([ StructField("id", StringType(), True), StructField("employeeNumber", StringType(), True) ]), True) ]), True) ]) # Read JSON data with multiline option and schema df = spark.read.option("multiline", "true").json("Files/testing.json", schema=schema) df = df.withColumn("ManagerId", coalesce(col("positionData.manager.id"), lit(None))) display(df)
Please try this and let me know if you have further queries.
While I have not tried it, I don't think it is going to work, as is:
>>In this example, coalesce will first try to access the value of the column "positionData.manager.id". If it's null, it will return None instead.<<
This issue is NOT that there is a NULL value in column "positionData.manager.id" it is that the column does not exist, cannot be found. If it is there at all, it is part of some nested JSON structure.
If I have data like this picture from the original post:
and I try to reference col("positionData.manager.id") then I get this error:
AnalysisException: [INVALID_EXTRACT_BASE_FIELD_TYPE] Can't extract a value from "manager". Need a complex type [STRUCT, ARRAY, MAP] but got "STRING".
It might be possible to use nested COALESCE statements and / or WHEN/OTHERWISE functions.
I'm going to have to experiment. Thanks for the tip.