json - 嵌套存储在字符串变量中的 JSON 对象

标签 json sql-server

如果我想将 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/

相关文章:

asp.net - T-SQL 检查重复的 field1 值但不同的 field2 值

java - 安卓/SQL服务器: Set Text to "No time" if the data at database is NULL

json - Node JS Joi 验证 - 如何返回 JSON 响应而不是字符串?

javascript - 计算对象数组上的所有值 - javascript

json - 更新到 Xcode 8.1 : Can no longer convert JSON data of type AnyObject to expected Type

mysql - 将 SQL Server 查询结果格式化为 3D 直方图

c# - json.net 有关键方法吗?

javascript - 如何将json字符串解析为javascript对象

SQL唯一字段: concurrency bugs?

sql - 使用来自另一个数据库的数据更新字段