TSQL:从JSON子属性中删除方括号

问题描述 投票:0回答:1

我有以下SQL查询来创建JSON。我使用WITHOUT_ARRAY_WRAPPER,因此根目录不会创建数组。

select *
from Documents D
join Notices Notice ON Notice.DocumentID = D.DocumentID
join NoticeDetails NoticeDetail on NoticeDetail.DocumentID = d.DocumentID
where d.DocumentID = 1234
FOR JSON Auto,WITHOUT_ARRAY_WRAPPER,INCLUDE_NULL_VALUES

上面的查询产生以下JSON。 (为简洁起见,我删除了一些json属性)

{
    "DocumentID": 1234,
    "ClientID": 3,  
    "Notice": [
        {
            "DocumentID": 1234,
            "StateCode": null,          
            "NoticeDetail": [
                {
                    "NoticeDetailID": 80122,
                    "DocumentID": 1234,                             
                    "CreatedDateTime": "2020-03-26T16:08:40.730",
                    "ModifiedDateTime": "2020-03-26T16:08:40.730"               
                }
            ]
        }
    ]
}

DocumentIDDocuments表中为PK,在NoticesNoticeDetails表中为FK。也是Notices表中的UNIQUE KEY。因此,基本上DocumentsNotices是1到1的关系。所以我不希望Notice属性成为输出json中的数组。

我的预期输出json应该是

{
    "DocumentID": 1234,
    "ClientID": 3,  
    "Notice": 
        {
            "DocumentID": 1234,
            "StateCode": null,          
            "NoticeDetail": [
                {
                    "NoticeDetailID": 80122,
                    "DocumentID": 1234,                                         
                    "CreatedDateTime": "2020-03-26T16:08:40.730",
                    "ModifiedDateTime": "2020-03-26T16:08:40.730"               
                }
            ]
        }       
}

我应该使用什么SQL来获得预期的输出?

tsql sql-server-2017 for-json
1个回答
0
投票

我想我找到了。基于SO POST here

select *,
JSON_QUERY((
    SELECT *
    ,JSON_QUERY((
        SELECT * FROM NoticeDetails NoticeDetail
        WHERE NoticeDetail.DocumentID = D.DocumentID
        FOR JSON PATH
    )) AS NoticeDetail
    FROM Notices Notice
    WHERE Notice.DocumentID = d.DocumentID
    FOR JSON PATH,WITHOUT_ARRAY_WRAPPER
)) AS NOTICE
from Documents D
where d.DocumentID = 1234
FOR JSON PATH,WITHOUT_ARRAY_WRAPPER,INCLUDE_NULL_VALUES
© www.soinside.com 2019 - 2024. All rights reserved.