Priyanka Khairnar
Priyanka Khairnar

Reputation: 366

Loop through JSON in SQL Server 2016

I have a following JSON

{
  "href": {
    "host": "localhost",
    "port": 2222
  },
  "name": "20190812",
  "scheduledStartTime": "2019-08-12T12:22:52.500-04:00",
  "parameters": {
    "1251226": {
      "value": {
        "instanceID": 219002,
        "productName": "product1",
        "userID": "admin"
      }
    },
    "1251287": {
      "value": {
        "sgName": "sg1",
        "userID": "admin"
      }
    }
  }
}

I want to iterate over the JSON and process the every iteration one by one. I tried using While giving the length of JSON as count, but couldn't figure out how to get values one by one

Is it even possible in SQL Server 2016?

I tried this so far

Declare @count INT
select @count = COUNT(*) 
FROM OPENJSON((select template_data_mapping from template_data_mapping), N'$')

WHILE @count != 0
BEGIN
   SELECT @count
   SET @count = @count - 1;
END;

Upvotes: 1

Views: 1329

Answers (1)

Zhorov
Zhorov

Reputation: 29983

It's not clear why you ...want to iterate over the JSON and process the every iteration one by one... using a WHILE loop, but one possible set-based approach to parse this JSON is to use the built-in JSON support:

JSON:

DECLARE @json nvarchar(max) = N'{
  "href": {
    "host": "localhost",
    "port": 2222
  },
  "name": "20190812",
  "scheduledStartTime": "2019-08-12T12:22:52.500-04:00",
  "parameters": {
    "1251226": {
      "value": {
        "instanceID": 219002,
        "productName": "product1",
        "userID": "admin"
      }
    },
    "1251287": {
      "value": {
        "sgName": "sg1",
        "userID": "admin"
      }
    }
  }
}'

Statement:

SELECT 
   j1.host, j1.port, j1.scheduledStartTime, 
   j2.[key] AS parameter, 
   j3.[key], j3.[value]
FROM OPENJSON(@json) WITH (
   host varchar(100) '$.href.host',
   port int '$.href.port',
   name varchar(100) '$.name',
   scheduledStartTime varchar(30) '$.scheduledStartTime',
   parameters nvarchar(max) '$.parameters' AS JSON
) j1
OUTER APPLY OPENJSON(j1.parameters, '$') j2
OUTER APPLY OPENJSON(j2.[value], '$.value') j3

Result:

host        port    scheduledStartTime              parameter   key         value   
localhost   2222    2019-08-12T12:22:52.500-04:00   1251226     instanceID  219002  
localhost   2222    2019-08-12T12:22:52.500-04:00   1251226     productName product1
localhost   2222    2019-08-12T12:22:52.500-04:00   1251226     userID      admin   
localhost   2222    2019-08-12T12:22:52.500-04:00   1251287     sgName      sg1    
localhost   2222    2019-08-12T12:22:52.500-04:00   1251287     userID      admin   

Upvotes: 1

Related Questions