Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse JSON Column containing multiple arrays

I’m trying to get this result but I’m not getting it. I’ve searched the forum but I can’t find a solution to my problem. Can you help me and explain what is wrong with my query?
thanks.

JSON

{
  "items": [
    {
      "id": 40054,
      "categories": [
        [
          28,
          168,
          53
        ]
      ]
    }
  ]
}

SQL

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   Declare @JSON varchar(max)
    SELECT @JSON=BulkColumn
    FROM OPENROWSET (BULK 'C:\temp\test.json', SINGLE_CLOB) import
    INSERT INTO dbo.TABLE
    SELECT
        metadata.[id],
        categories.[categories1],
        categories.[categories2],
        categories.[categories3],
        getdate() as [dt_imp] FROM OPENJSON (@JSON)
    WITH(
        [items] NVARCHAR(MAX) AS JSON
        ) AS  Data
    
    OUTER APPLY OPENJSON([Data].[items])
    WITH(
        [id] NVARCHAR(MAX),
        [categories] NVARCHAR(MAX) AS JSON
        ) AS metadata
    
    OUTER APPLY OPENJSON([Metadata].[categories])
    WITH(   
        [categories1] NVARCHAR(MAX),
        [categories2] NVARCHAR(MAX),
        [categories3] NVARCHAR(MAX)
        ) AS categories

result I want

id categories1 categories2 categories3
40054 28 168 53

>Solution :

Perhaps this will help.

Updated to allow multiple arrays within the array.

Select ID   = json_value(A.value,'$.id')
      ,cat1 = json_value(B.value,'$[0]')
      ,cat2 = json_value(B.value,'$[1]')
      ,cat3 = json_value(B.value,'$[2]')
 From  OpenJSON(@JSON,'$.items') A
 Cross Apply OpenJSON(A.value,'$.categories') B

Results

ID      cat1    cat2    cat3
40054   28      168     53
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading