I have the following Json:
{
"archeTypes": [
{
"archeTypeId": 12,
"elements": [
{
"elementId": 6,
"value": "string6"
},
{
"elementId": 7,
"value": "string7"
}
]
}
]
}
Here is my code:
DECLARE @json NVARCHAR(MAX);
SET @json='{"archeTypes":[{"archeTypeId":12,"elements":[{"elementId":6,"value":"string6"},{"elementId":7,"value":"string7"}]}]}';
SELECT *
FROM OPENJSON(@json)
WITH (
ArcheTypeId INT '$.archeTypes.archeTypeId',
ElementId INT '$.archeTypes.elements.elementId',
Value NVARCHAR(max) '$.archeTypes.elements.value'
);
Here is the table that I want to:
ArcheTypeId | ElementId | Value |
---|---|---|
12 | 6 | string6 |
12 | 7 | string7 |
How can I convert the json to table?
CodePudding user response:
Does this help? (using cross apply
)
DECLARE @json NVARCHAR(MAX);
SET @json='{"archeTypes":[{"archeTypeId":12,"elements":[{"elementId":6,"value":"string6"},{"elementId":7,"value":"string7"}]}]}';
SELECT archeTypes.ArcheTypeId,elements.ElementId,elements.Value
FROM OPENJSON(@json)
WITH
(
archeTypes nvarchar(max) as JSON
) as archeType cross apply
OPENJSON(archeType.archeTypes)
WITH
(
archeTypeId INT,
elements nvarchar(max) as JSON
) as archeTypes cross apply
OPENJSON(archeTypes.elements)
WITH
(
elementId INT,
value nvarchar(max)
) as elements
;