How to parse JSON with TSQL
I've done some basic JSON parsing before in TSQL but am running into something a bit more complex.
The actual field within the JSON object I'm attempting to parse is an array with two objects in it.
For example:
{
"Channel":[],
"Account":[],
"OrderId": 4568,
"ParentAccount"null,
"Groups":[
{"Name":"List 1", "Include": false, "SalesDetails"[{
"Manufacturer":[], "DateRange":{"Start":"01/01/2021", "End:"12/31/2021"},
"State":"NC"}]
},
{"Name":"List 2", "Include": true, "SalesDetails"[{
"Manufacturer":[], "DateRange":{"Start":"01/01/2022", "End:"01/10/2022"},
"State":"SC"}]
}
],
"IsCustomer":true,
"ReferenceNumber": 554673
}
What I'd like to do within SQL is parse out the account, order id, and then the groups. Does anyone know how to parse out the multiple objects within the groups array? That's the part I haven't got.
My goal is to have a report where each order is on a single row.
order | groups object 1 name | groups object 2 name |
---|---|---|
4568 | list 1 | list 2 |
I'm trying to get the other values between the names such as Include and have the SalesDetail be their own column.
So far the following has gotten me closest to what i'm after:
SELECT
JSON_QUERY(data, '$.account') AS 'Account',
JSON_QUERY(data, '$.orderid') AS 'Order',
JSON_QUERY(data, '$.groups') AS 'Group_Detail'
FROM table
I haven't gotten the info within the groups field parsed out into their own individual column though.
Assuming I correctly fixed the serialization issues, maybe something like this
declare @json nvarchar(max)=N'{
"Channel":[],
"Account":[],
"OrderId": 4568,
"ParentAccount":null,
"Groups":[
{"Name":"List 1", "Include": false, "SalesDetails":[{
"Manufacturer":[], "DateRange":{"Start":"01/01/2021", "End":"12/31/2021"},
"State":"NC"}]
},
{"Name":"List 2", "Include": true, "SalesDetails":[{
"Manufacturer":[], "DateRange":{"Start":"01/01/2022", "End":"01/10/2022"},
"State":"SC"}]
}
],
"IsCustomer":true,
"ReferenceNumber": 554673
}';
select OrderId,
grp1.[Name] [groups object 1 name],
grp2.[Name] [groups object 2 name]
from openjson(@json) with (OrderId int,
Groups nvarchar(max) as json) oj
cross apply openjson(oj.Groups, '$[0]') with ([Name] nvarchar(4000)) grp1
cross apply openjson(oj.Groups, '$[1]') with ([Name] nvarchar(4000)) grp2;
OrderId groups object 1 name groups object 2 name
4568 List 1 List 2