简体   繁体   中英

extract json column using spark.sql in azure synapse notebook

I have a parquet file as source and I loaded that parquet file using PySpark notebook as shown below:

df_Employee = spark.read.parquet(<filename>)
df_Employee .createOrReplaceTempView("employee_data")

here's how the table looks like


Employee Table:

-Name
-Salary
-Company
-Address (datatype=string)
 --street.name
 --street.number
 --postalcode
-JoiningDate

I have the following code but I'm stuck on how to extract street.name & street.number from the above SQL table, here's what I have

df=spark.sql(f'''
select Name, Salary, Company, json_extract(Address,'$."street.name"') as StreetName
from employee_data
''')

but json_extract(Address,'$."street.name"') as StreetName throws an error. How to extract this nested json field?

I reproduce the same in my environment created sample data frame as per Employee Table:

dat1= [("vamsi", 20000, "MID", '{"street.name": "App socity", "street.number": "912", "postalcode": "523112"}', "2023-01-20"),
        ("rakesh",30000, "MID", '{"street.name": "Mind space", "street.number": "456", "postalcode": "600062"}', "2023-01-19")]
col = ["Name", "Salary", "Company", "Address", "JoiningDate"]

df1 = spark.createDataFrame(dat1, col)
df1.createOrReplaceTempView("sample_table")

在此处输入图像描述

You can achieve the same requirement using the following code .

df1 = spark.sql(f'''select Name, Salary, Company, json_tuple(Address, 'street.name', 'street.number') as (StreetName, StreetNumber)
from sample_table''')
df1.show()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM