Skip to content
Advertisement

JSON SQL Server 2016 parse

I have a nested JSON as output form a form and I need to parse it in order to send it in joined tables. I cannot parse some of the data I have in the JSON: labels, rangesValues or body I get NULL anyone encountered this type?

    DECLARE @json NVARCHAR(MAX)
SET @json = '{
   "Id":"712db489",
   "label":"kjk",
   "ranges":{
      "rangeQuestion":null,
      "minRange":0,
      "maxRange":10,
      "rangeValues":[1,2],
      "hasMarks":false
   },
   "labels":[1,2],
   "options":[
      {
         "body":"Yes",
         "sequence":1
      },
      {
         "body":"No",
         "sequence":2
      }
   ]
}'

SELECT * FROM  
 OPENJSON ( @json )  
WITH (   
              label   nvarchar(250), --ok
              maxRange   nvarchar(250) '$.ranges.maxRange', --ok
              labels   nvarchar(250), -- not parsed
              rangesValues nvarchar(250) '$.ranges.rangeValues' , -- not parsed
              body   nvarchar(250) '$.options.body' -- not parsed

 ) 

the output should be like

minRange maxRange rangeValues
0 10 1
0 10 2

body sequence

Yes 1

No 2

And what can be done if there are 3 levels nested?

DECLARE @json NVARCHAR(MAX)

SET @json = '{
   "Id":"712db489",
   "label":"kjk",
   "ranges":{
      "rangeQuestion":null,
      "minRange":0,
      "maxRange":10,
      "rangeValues": [
                {
                    "rangeValue": 1,
                    "otherValue": 10
                },
                {
                    "rangeValue": 2,
                    "otherValue": 20
                }
            ],
      "hasMarks":false
   },
   "labels":[1,2],
   "options":[
      {
         "body":"Yes",
         "sequence":1
      },
      {
         "body":"No",
         "sequence":2
      }
   ]
}'

SELECT r.minRange,
       r.maxRange,
       rV.[value] AS rangeValue
FROM OPENJSON (@json, '$.ranges')  
     WITH (minRange int,
           maxRange int,
           rangeValues nvarchar(MAX) 
           AS JSON) r
     CROSS APPLY OPENJSON (r.rangeValues) rV;

Advertisement

Answer

Seems like, from the discussion in the comments, what you are actually after is this:

SELECT r.minRange,
       r.maxRange,
       rV.[value] AS rangeValue
FROM OPENJSON (@json, '$.ranges')  
     WITH (minRange int,
           maxRange int,
           rangeValues nvarchar(MAX) AS JSON) r
     CROSS APPLY OPENJSON (r.rangeValues) rV;

SELECT *
FROM OPENJSON (@json,'$.options')
     WITH (body varchar(3),
           sequence int) o;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement