[英]SQL Server parse nested json using OPENJSON
I am trying to read JSON that I would like to parse each collection in SQL Server.我正在尝试读取 JSON,我想解析 SQL 服务器中的每个集合。
The structure is as follows Root > Action > GoActionFiles / Pools结构如下 Root > Action > GoActionFiles / Pools
I would like to return a row for each GoActionFiles > GoActionFile, so it looks like the below;我想为每个 GoActionFiles > GoActionFile 返回一行,所以它看起来像下面这样;
The JSON is as follows; JSON如下;
DECLARE @Json NVARCHAR(MAX)
SET @Json =
N'
{
"Root":{
"Action":{
"ActionId":1,
"OutcomeId":2,
"ActionDateTime":"2022-11-22T14:28:20.9700312+00:00",
"GoActionFiles":{
"GoActionFile":[
{
"Name":"Arigon",
"Status":"Failed"
},
{
"Name":"Butella",
"Status":"Passed"
},
{
"Name":"Chantice",
"Status":"Passed"
},
{
"Name":"Fordwat",
"Status":"Passed"
}
]
},
"Pools":{
"Pool":[
{
"Name":"Arigon",
"Status":"Passed"
},
{
"Name":"Butella",
"Status":"Failed"
},
{
"Name":"Chantice",
"Status":"Failed"
},
{
"Name":"Fordwat",
"Status":"Failed"
}
]
},
"ExtCheck":{
"Score":800,
"ExtStatus":"Passed",
"IntScore":0
}
}
}
'
I have tried the following SQL so far;到目前为止,我已经尝试了以下 SQL;
SELECT ActionId, a.GoActionFiles FROM OPENJSON(@Json, '$.Root.Action') WITH
(
ActionId INT,
GoActionFiles NVARCHAR(MAX) AS JSON
) AS a
If only one actionID I suspect this would be more performant如果只有一个 actionID,我怀疑这会更高效
Select ActionID = JSON_VALUE(@Json,'$.Root.Action.ActionId')
,GoActionFileName = [Name]
,GoActionFileStatus = [Status]
From OpenJSON(@Json, '$.Root.Action.GoActionFiles.GoActionFile')
with ( [Name] varchar(150),
[Status] varchar(150)
) AS a
If Multiple ID's如果多个ID
SELECT A.ActionId
,GoActionFileName = B.[Name]
,GoActionFileStatus = B.[Status]
FROM OPENJSON(@Json, '$.Root.Action') WITH (
ActionId INT,
GoActionFiles NVARCHAR(MAX) AS JSON
) A
Cross Apply ( Select *
From OpenJSON(GoActionFiles, '$.GoActionFile')
with ( [Name] varchar(150),
[Status] varchar(150)
) B1
) B
Both Return两者都返回
ActionId GoActionFileName GoActionFileStatus
1 Arigon Failed
1 Butella Passed
1 Chantice Passed
1 Fordwat Passed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.