如何在SQL Server中正确解压缩JSON数组

时间:2019-06-28 15:53:01

标签: json azure-sql-database

我正在涉足JSON,我想将用户添加到多个组:将JSON数组插入表中。

理想情况下,JSON如下所示:

'{
"Email": "WMogh@starfleet.gov",
"Prefix":null,
"FirstName": "Worf",
"MiddleInitial": "",
"LastName": "Mogh",
"Suffix": "Son Of",
"Title" :"Commander",
"Groups": [{"0", "1", "5"}]
"Better_Groups": [{"ID":"0", "ID":"1", "ID":"5"}]
}' 

目前,我可以像这样使用JSON:

'{
"Email": "WMogh@starfleet.gov",
"Prefix":null,
"FirstName": "Worf",
"MiddleInitial": "",
"LastName": "Mogh",
"Suffix": "Son Of",
"Title" :"Commander",
"Groups": "1,2,3,4"
}' 

然后使用以下内容“解压”它:

declare @groups varchar(1000)

select @groups = Groups from openjson(@json)
                WITH
        (

        Groups nvarchar(100)        '$.Groups'
        )

        print @groups

select value from string_split(@groups, ',')

它返回一个漂亮的小表,如下所示:

Value
1
2
3
4

问题这是错误的JSON,Web开发人员会取笑我。

问题您如何在SQL Server中正确解压缩JSON数组?

更新:

最终使用的JSON如下所示:

    @json =
            '{
            "Email": "WMogh@starfleet.gov",
            "Prefix":null,
            "FirstName": "Worf",
            "MiddleInitial": "",
            "LastName": "Mogh",
            "Suffix": "Son Of",
            "Title" :"Commander",
            "Groups": "1,2,3,4",
            "Better_Groups": ["0", "1", "5"]
            }' 

1 个答案:

答案 0 :(得分:1)

假设“ groups”元素是一个数组:

DECLARE @json NVARCHAR(MAX) = 
N'{
"Email": "WMogh@starfleet.gov",
"Prefix":null,
"FirstName": "Worf",
"MiddleInitial": "",
"LastName": "Mogh",
"Suffix": "Son Of",
"Title" :"Commander",
"Better_Groups": ["0", "1", "5"]
}';

SELECT s.value
FROM OPENJSON(JSON_QUERY(@json, '$.Better_Groups')) s;

db<>fiddle demo