Possible options are: 1) Using OPENJSON()
twice (with default and explicit schema) and an additional APPLY
operator or 2) Using OPENJSON()
(with default schema) and JSON_VALUE()
:
JSON:
DECLARE @json nvarchar(max) = N'{
"projects":{
"project1id":{
"data":{
"customer":"Cust1",
"name":"Project Name 1"
},
"projectType":"type0"
},
"project2id":{
"data":{
"customer":"Customer 2",
"name":"Name 2",
"projectManager":"Man Ager"
},
"projectType":"type2"
},
"Project3id":{
"data":{
"customer":"Another Customer",
"name":"Another Project"
},
"projectType":"type1"
}
}
}'
Statement with OPENJSON()
and APPLY
operator:
SELECT j1.[key] AS projectId, j2.*
FROM OPENJSON(@json, '$.projects') j1
CROSS APPLY OPENJSON(j1.[value], '$') WITH (
name nvarchar(max100) '$.data.name',
customer nvarchar(max100) '$.data.customer',
projectType nvarchar(max100) '$.projectType',
projectManager nvarchar(max100) '$.data.projectManager'
) j2
Statement with OPENJSON()
and JSON_VALUE()
:
SELECT
projectId = [key],
name = JSON_VALUE([value], '$.data.name'),
customer = JSON_VALUE([value], '$.data.customer'),
projectType = JSON_VALUE([value], '$.projectType'),
projectManager = JSON_VALUE([value], '$.data.projectManager')
FROM OPENJSON(@json, '$.projects')