Forum Discussion
How to reference a JSON array element with no name using a Notebook or OPENROWSET?
- 5 months ago
Hi Richtpt ,
Thanks for reaching out to the Microsoft Fabric Community forum.If you just want to see the data in the same nested format as it appears in the JSON, you can run:
df.select("PRCCollection.Modifiers").show()Since both PRCCollection and Modifiers are arrays, Spark will display the result as something like [[US]]. That simply means there is an array inside another array.
If you’d prefer to flatten the structure and extract the actual value, you can use explode() to expand each array level:
from pyspark.sql.functions import explode df2 = df.withColumn("prc", explode("PRCCollection")) \ .withColumn("Modifier", explode("prc.Modifiers")) df2.select("Modifier").show()Here, the first explode() opens up the PRCCollection array, and the second one expands the Modifiers array inside it. The output will then show the value directly (for example US) instead of the nested [[US]] structure.
For reference this is the output of df.schema() for my data
I hope this information helps. Please do let us know if you have any further queries.
Thank you
Modifier is an array, the value inside it is accessed by index number, not by name. firsy value is at index[0].
to get the value use code { df.select("PRC0Collection.Modifiers[0]").show() }
May be this can help.
Thanks but this isn't working for me. I have
df = spark.read.json("file1.json")
df.select("PRC0Collection.Modifiers[0]").show()
I get this error: [FIELD_NOT_FOUND] No such struct field `Modifiers[0]` in `Cache_ID`, `Exp_Date`, `Modifiers`, `PSCD_ID`, `Price`, `Type`.