I'm using pyspark 3.1.1 and python 3.8
I have a json file in input like this:
{"id" :1, "field_a": "test"}
{"id" :2, "field_a": "test", "field_b": "z"}
{"id" :3, "field_a": "test", "field_b": null}
When I try to read the file using spark, it automatically fills the missing column field_b for the first record to null.
spark = SparkSession \
.builder \
.appName("Python Spark SQL basic example") \
.getOrCreate()
df = spark.read.json('my_file.json').show()
Will return:
+-------+-------+---+
|field_a|field_b| id|
+-------+-------+---+
| test| null| 1|
| test| z| 2|
| test| null| 3|
+-------+-------+---+
In this way I cannot distinguish the records that have NULL as a value and those that don't have the field at all.
I know that is possible to check if a column exists using df.columns but that will return the columns of the entire dataframe so it doesn't help me.
I want a function like this:
df = df.withColumn("column_in_json", record_has_column(field_b))
with an output like this:
+-------+-------+---+--------------+
|field_a|field_b| id|column_in_json|
+-------+-------+---+--------------+
| test| null| 1| false|
| test| z| 2| true|
| test| null| 3| true|
+-------+-------+---+--------------+