Issue
I have this json which I want to use to create the columns in dataframe:
json:
{
"Version": "V1",
"Fruit1": {
"Apple": 60.0,
"Orange": 60.0,
"Melon": 60.0
},
"Fruit2": {
"Strawberry": 40.0,
"Orange": 60.0,
"Melon": 40.0
},
"Fruit3": {
"Apple": 90.0,
"Orange": 90.0,
"Melon": 95.0
}
}
The number of layers for Fruit could increase or decrease, like there can be another layer Fruit4 or there can only be one layer in this json which is Fruit1. The number of fruit names are fixed. I want to construct this dataframe out of it. Anyy help would be really appreciated.
Version Name Apple Orange Melon Strawberry
V1 Fruit1 60 60 60 null
V1 Fruit2 null 60 40 40
V1 Fruit3 90 90 95 null
Solution
If the jsons are stored in a file, you can read it using spark.read.json() and further process it.
I've added a new row (a new json) with version="V2" and few additional fruits to your example data, and the same is stored in a file.
Reading the json file (source at the bottom)
multiline_json_sdf = spark.read. \
option('multiLine', 'true'). \
json('./path/to/file_with_jsons.json')
# +------------------+------------------+------------------------+------------------+-------+
# |Fruit1 |Fruit2 |Fruit3 |Fruit4 |Version|
# +------------------+------------------+------------------------+------------------+-------+
# |{60.0, 60.0, 60.0}|{40.0, 60.0, 40.0}|{90.0, 95.0, 90.0, null}|null |V1 |
# |{60.0, 60.0, 60.0}|{40.0, 60.0, 40.0}|{90.0, 95.0, null, 90.0}|{90.0, 95.0, 90.0}|V2 |
# +------------------+------------------+------------------------+------------------+-------+
# root
# |-- Fruit1: struct (nullable = true)
# | |-- Apple: double (nullable = true)
# | |-- Melon: double (nullable = true)
# | |-- Orange: double (nullable = true)
# |-- Fruit2: struct (nullable = true)
# | |-- Melon: double (nullable = true)
# | |-- Orange: double (nullable = true)
# | |-- Strawberry: double (nullable = true)
# |-- Fruit3: struct (nullable = true)
# | |-- Apple: double (nullable = true)
# | |-- Melon: double (nullable = true)
# | |-- Orange: double (nullable = true)
# | |-- Squash: double (nullable = true)
# |-- Fruit4: struct (nullable = true)
# | |-- Apple: double (nullable = true)
# | |-- Banana: double (nullable = true)
# | |-- Orange: double (nullable = true)
# |-- Version: string (nullable = true)
My approach is to flatten the data, and then unpivot it so that all column values are in rows against their fruit names. The long data can then be pivoted as per requirements.
Flatten the data
# extract fruit columns and their struct fields
fruit_cols = [k for k in multiline_json_sdf.columns if 'fruit' in k.lower()]
fruitcol_struct_fields = {}
for fruit in fruit_cols:
# dict[fruit column name] = [(old field name, fruit column name + old field name, ...]
fruitcol_struct_fields[fruit] = [(k, fruit + '_' + k) for k in multiline_json_sdf.select(func.col('{0}.*'.format(fruit))).columns]
# use the aforementioned to iterate and create new columns in dataframe
flattened_json_sdf = multiline_json_sdf. \
select('version',
*reduce(lambda x, y: x + y, [[func.col('{}.'.format(fruit)+k[0]).alias(k[1])
for k in fruitcol_struct_fields[fruit]]
for fruit in fruit_cols]
)
)
# +-------+------------+------------+-------------+------------+---+-------------+-------------+
# |version|Fruit1_Apple|Fruit1_Melon|Fruit1_Orange|Fruit2_Melon|...|Fruit4_Banana|Fruit4_Orange|
# +-------+------------+------------+-------------+------------+---+-------------+-------------+
# |V1 |60.0 |60.0 |60.0 |40.0 |...|null |null |
# |V2 |60.0 |60.0 |60.0 |40.0 |...|95.0 |90.0 |
# +-------+------------+------------+-------------+------------+---+-------------+-------------+
The list comprehension within the select creates new columns using the struct fields - fruit1.Apple as fruit1_Apple, ..., fruit4.Orange as fruit4_Orange.
This flattened data can be transposed down and then pivoted back using the fruit names.
flattened_json_sdf. \
withColumn('fruit_struct_arr',
func.array(*[func.struct(func.lit(k).alias('key'), func.col(k).alias('val'))
for k in flattened_json_sdf.columns if k != 'version']
)
). \
selectExpr('version', 'inline(fruit_struct_arr)'). \
withColumn('key_split', func.split('key', '_')). \
withColumn('name', func.col('key_split')[0]). \
withColumn('fruit_to_pivot', func.col('key_split')[1]). \
groupBy('version', 'name'). \
pivot('fruit_to_pivot'). \
agg(func.first('val')). \
show()
# +-------+------+-----+------+-----+------+------+----------+
# |version| name|Apple|Banana|Melon|Orange|Squash|Strawberry|
# +-------+------+-----+------+-----+------+------+----------+
# | V1|Fruit2| null| null| 40.0| 60.0| null| 40.0|
# | V1|Fruit1| 60.0| null| 60.0| 60.0| null| null|
# | V1|Fruit4| null| null| null| null| null| null|
# | V2|Fruit4| 90.0| 95.0| null| 90.0| null| null|
# | V1|Fruit3| 90.0| null| 95.0| 90.0| null| null|
# | V2|Fruit2| null| null| 40.0| 60.0| null| 40.0|
# | V2|Fruit1| 60.0| null| 60.0| 60.0| null| null|
# | V2|Fruit3| 90.0| null| 95.0| null| 90.0| null|
# +-------+------+-----+------+-----+------+------+----------+
fruit_struct_arr is an array of column structs that has the column name as "key" and column value as "val". Use the SQL inline() function to explode it and create 2 columns - key, val - along with the version provided in the selectExpr. Use the newly created key column to extract the fruit names and the identifier - split can be used with "_" as delimiter. Once extracted, they can be pivoted to get the required data format.
source JSON file
[{
"Version": "V1",
"Fruit1": {
"Apple": 60.0,
"Orange": 60.0,
"Melon": 60.0
},
"Fruit2": {
"Strawberry": 40.0,
"Orange": 60.0,
"Melon": 40.0
},
"Fruit3": {
"Apple": 90.0,
"Orange": 90.0,
"Melon": 95.0
}
},
{
"Version": "V2",
"Fruit1": {
"Apple": 60.0,
"Orange": 60.0,
"Melon": 60.0
},
"Fruit2": {
"Strawberry": 40.0,
"Orange": 60.0,
"Melon": 40.0
},
"Fruit3": {
"Apple": 90.0,
"Squash": 90.0,
"Melon": 95.0
},
"Fruit4": {
"Apple": 90.0,
"Orange": 90.0,
"Banana": 95.0
}
}]
print(fruit_cols)
# ['Fruit1', 'Fruit2', 'Fruit3', 'Fruit4']
print(fruitcol_struct_fields)
# {'Fruit1': [('Apple', 'Fruit1_Apple'),
# ('Melon', 'Fruit1_Melon'),
# ('Orange', 'Fruit1_Orange')],
# 'Fruit2': [('Melon', 'Fruit2_Melon'),
# ('Orange', 'Fruit2_Orange'),
# ('Strawberry', 'Fruit2_Strawberry')],
# 'Fruit3': [('Apple', 'Fruit3_Apple'),
# ('Melon', 'Fruit3_Melon'),
# ('Orange', 'Fruit3_Orange'),
# ('Squash', 'Fruit3_Squash')],
# 'Fruit4': [('Apple', 'Fruit4_Apple'),
# ('Banana', 'Fruit4_Banana'),
# ('Orange', 'Fruit4_Orange')]}
flattened_json_sdf. \
withColumn('fruit_struct_arr',
func.array(*[func.struct(func.lit(k).alias('key'), func.col(k).alias('val'))
for k in flattened_json_sdf.columns if k != 'version']
)
). \
select('version', 'fruit_struct_arr'). \
show(truncate=50)
# +-------+--------------------------------------------------+
# |version| fruit_struct_arr|
# +-------+--------------------------------------------------+
# | V1|[{Fruit1_Apple, 60.0}, {Fruit1_Melon, 60.0}, {F...|
# | V2|[{Fruit1_Apple, 60.0}, {Fruit1_Melon, 60.0}, {F...|
# +-------+--------------------------------------------------+
# root
# |-- version: string (nullable = true)
# |-- fruit_struct_arr: array (nullable = false)
# | |-- element: struct (containsNull = false)
# | | |-- key: string (nullable = false)
# | | |-- val: double (nullable = true)
flattened_json_sdf. \
withColumn('fruit_struct_arr',
func.array(*[func.struct(func.lit(k).alias('key'), func.col(k).alias('val'))
for k in flattened_json_sdf.columns if k != 'version']
)
). \
selectExpr('version', 'inline(fruit_struct_arr)'). \
withColumn('key_split', func.split('key', '_')). \
withColumn('name', func.col('key_split')[0]). \
withColumn('fruit_to_pivot', func.col('key_split')[1]). \
show(5)
# +-------+-------------+----+----------------+------+--------------+
# |version| key| val| key_split| name|fruit_to_pivot|
# +-------+-------------+----+----------------+------+--------------+
# | V1| Fruit1_Apple|60.0| [Fruit1, Apple]|Fruit1| Apple|
# | V1| Fruit1_Melon|60.0| [Fruit1, Melon]|Fruit1| Melon|
# | V1|Fruit1_Orange|60.0|[Fruit1, Orange]|Fruit1| Orange|
# | V1| Fruit2_Melon|40.0| [Fruit2, Melon]|Fruit2| Melon|
# | V1|Fruit2_Orange|60.0|[Fruit2, Orange]|Fruit2| Orange|
# +-------+-------------+----+----------------+------+--------------+
# only showing top 5 rows
Answered By - samkart Answer Checked By - Mildred Charles (sql.easybugfix Admin)
Post a Comment
Post a Comment