Forum Discussion
Reading json from notebook
- Anonymous2 years ago
Hi ThiyagarajanLG ,
Can you please try the below code -from pyspark.sql.types import StructType, StructField, StringType, ArrayType from pyspark.sql.functions import col, coalesce, lit, explode # Define the schema schema = StructType([ StructField("SEMPermID", StringType(), True), StructField("Contents", ArrayType( StructType([ StructField("MetaData", StringType(), True), StructField("Payload", ArrayType( StructType([ StructField("FileName", StringType(), True), StructField("ObjectId", StringType(), True), StructField("MimeType", StringType(), True), StructField("Language", StringType(), True), StructField("FileCreated", StringType(), True), ]) ), True), ]) ), True), ]) # Read the JSON data with the defined schema df3 = spark.read.option("multiline", "true").json("Files/testing2.json", schema=schema) # Explode the "Contents" array df3 = df3.withColumn("Contents", explode("Contents")) # Perform transformations to Payload and MetaData df3 = df3.withColumn("Payload", coalesce(col("Contents.Payload"), lit(None))) df3 = df3.withColumn("MetaData", coalesce(col("Contents.MetaData"), lit(None))) # Select only the required columns df3 = df3.select("SEMPermID", "MetaData", "Payload") display(df3)
FYI: In my case provided input json is in testing2.json file.
Hope this is helpful. Please let me know incase of further queries.
hi,
I tried with some other json file. The json file as below
----------------------------
{
"container_records": [
{
"state": {
"effectiveFrom": "2023-11-23T07:30:00.000Z",
"effectiveTo": "2024-04-16T14:50:44.231Z",
"currentFrom": "2023-11-23T10:45:25.953Z",
"currentTo": null,
"aDataItem": {
"distinguishingEventName": "Q3 2024 AAC Clyde Space AB Earnings Release",
"EventTypeId": 1000351539,
}
}
},
{
"state": {
"effectiveFrom": "2024-04-16T14:50:44.231Z",
"effectiveTo": null,
"currentFrom": "2023-11-23T10:45:25.953Z",
"currentTo": "2024-04-16T14:50:44.810Z",
"aDataItem": {
"distinguishingEventName": "Q3 2024 AAC Clyde Space AB Earnings Release",
"EventTypeId": 1000351539,
}
}
},
{
"state": {
"effectiveFrom": "2024-04-16T14:50:44.231Z",
"effectiveTo": null,
"currentFrom": "2024-04-16T14:50:44.810Z",
"currentTo": null,
"aDataItem": {
"distinguishingEventName": "Q3 2024 AAC Clyde Space AB Earnings Release",
"EventTypeId": 1000351539,
}
}
}
]
}
------------------------------------
my pyspark code is below.
- Anonymous2 years agoNot applicable
Hi ThiyagarajanLG ,
Can you please raise new thread for this query? So I can look into it closely..
After creating new thread link, please share it here.
Thank you