如果我想将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 should not用引号括起来,字符被转义.

{"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

Returns

{
  "EmployeeInformation": {
    "Company": "00500",
    "Employee": "10000"
  },
  "Other Data": "other data"
}

Instead of

{
  "EmployeeInformation": "{\"Company\":\"00500\",\"Employee\":\"10000\"}",
  "Other Data": "other data"
}

Json相关问答推荐

使用Shell深入挖掘到最低的SON元素

如何获取brew list作为JSON输出

Vega-Lite(Deneb):难以将最小和最大值应用于折线图和文本标签以及线条末尾的点

如何让JSON子查询在没有行的情况下返回空数组而不是NULL

在深度嵌套数组中使用布尔属性的jq-select

NoneType 对象的 Python 类型错误

如何将属性拆分为嵌套的JSON内容?

如何将 JSON 文本作为参数传递给 powershell?

将具有多个级别的 json 读入 DataFrame [python]

阅读 JSON 正文 Firebase 云函数

如何使用 boost::json::value 调用无参数函数

Jackson 的@JsonView、@JsonFilter 和 Spring

将带有数据和文件的 JSON 发布到 Web Api - jQuery / MVC

如何自动修复无效的 JSON 字符串?

Golang struct 的 XML 和 JSON 标签?

使用 Codable 序列化为 JSON 时的 Swift 字符串转义

如何使用 Javascript 将数据写入 JSON 文件

使用 jQuery 和 JSON 填充表单?

JSON.stringify 向我的 Json 对象添加额外的 \ 和 "" 的问题

如何从 github API 解析链接头