如果我想将 JSON 字符串作为变量传递,并使用 SQL Server 中的 FOR JSON PATH
将其嵌入到另一个 JSON 对象中,我该怎么做?
简明示例:
DECLARE @empInfo nvarchar(max), @msg nvarchar(max)
SET @empInfo = (SELECT '00500' as 'Company', '10000' as 'Employee' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)
SET @msg = (
SELECT
@empInfo as 'EmployeeInformation',
'other data' as 'Other Data'
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
)
SELECT @msg
在这种情况下,@msg 的格式会很糟糕。 EmployeeInformation 不应该包含引号,并且字符已被转义。
{"EmployeeInformation":"{\"Company\":\"00500\",\"Employee\":\"10000\"}","Other Data":"other data"}
最佳答案
将其包含在对 JSON_QUERY
的调用中因此它被视为 JSON 对象而不是字符串。
DECLARE @empInfo nvarchar(max), @msg nvarchar(max)
SET @empInfo = (SELECT '00500' as 'Company', '10000' as 'Employee' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)
SET @msg = (
SELECT
JSON_QUERY(@empInfo) as 'EmployeeInformation',
'other data' as 'Other Data'
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
)
SELECT @msg
返回
{
"EmployeeInformation": {
"Company": "00500",
"Employee": "10000"
},
"Other Data": "other data"
}
代替
{
"EmployeeInformation": "{\"Company\":\"00500\",\"Employee\":\"10000\"}",
"Other Data": "other data"
}
关于json - 嵌套存储在字符串变量中的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75476983/