4

I have a JSON structure like this:

Declare @layout NVARCHAR(MAX) = N'
    {
        "Sections": [
            {
                "SectionName":"Section1",
                "SectionOrder":1,
                "Fields":[
                    {
                        "FieldName":"Field1",
                        "FieldData":"Data1"
                    },
                    {
                        "FieldName":"Field2",
                        "FieldData":"Data2"
                    }
                ]
            },
            {
                "SectionName":"Section2",
                "SectionOrder":2,
                "Fields":[
                    {
                        "FieldName":"Field3",
                        "FieldData":"Data3"
                    },
                    {
                        "FieldName":"Field4",
                        "FieldData":"Data4"
                    }
                ]
            }
        ]
    }
'

How do I query to the equivalent of Sections.Fields.FieldName = 'Field3'?

select *
from OPENJSON(@layout,'$.Sections') 
WITH (
    SectionName nvarchar(MAX) '$.SectionName',  
    SectionOrder nvarchar(MAX) '$.SectionOrder', 
    Fields nvarchar(MAX) '$.Fields' as JSON
)

This is as far as I got, I can't go down any further or it will not return any results.

1 Answer 1

4

Figured it out after reading documentation, fully works!

SELECT SectionName, FieldName, FieldData FROM (
    select *
    from OPENJSON(@layout,'$.Sections') 
    WITH (
        SectionName nvarchar(MAX) '$.SectionName',  
        SectionOrder nvarchar(MAX) '$.SectionOrder', 
        Fields nvarchar(MAX) '$.Fields' as JSON
    )
) as Sections
CROSS APPLY OPENJSON(Fields,'$')
WITH (
    FieldName nvarchar(MAX) '$.FieldName',  
    FieldData nvarchar(MAX) '$.FieldData'
)
2
  • The documentation is a magical thing. Should always consult that first.
    – dfundako
    Commented Nov 7, 2016 at 22:38
  • Thanks! it was much easier to find the answer here than in the docs. By the way, you can also use the expanded syntax CROSS APPLY ( SELECT * FROM OPENJSON(Fields) WITH (FieldName nvarchar(max))) AS Fields which allows you to give it a table name. Commented Apr 2, 2019 at 21:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.