sql - 我可以在没有源列名成为 SQL Server 2016 键的情况下使用 FOR JSON 吗?

标签 sql json sql-server tsql

我有一个表,其中包含带有组 ID 的 json 字符串。我想创建一个包含所有具有相同 id 的 json 对象的 json 数组。

请注意,在我的情况下,我试图放入数组的列内容本身就是 json 片段,因此我的情况和问题比将行转换为数组更具体。 OPENJSON的使用在接受的答案中也利用了这个细节。

但是,我找不到使用 FOR JSON 的方法,该方法允许我选择单个列,而该列的名称不会成为数组中所有对象的键。

我意识到我试图摆脱的键是将列投影到 json 的键值表示的键所必需的,但在这种情况下,我只选择了一列,我很好奇是否有我不能的技巧考虑到。

我可以通过简单地使用 COALASCE 来实现我想要的,但我想知道是否可以使用 FOR JSON 处理这种边缘情况。这是演示我正在尝试执行的操作的简化代码:

BEGIN
    declare @Json_Snippets table (id int, json nvarchar(max));

    insert into @Json_Snippets (id, json) VALUES (1, '{"root":{"obj":"one"}}');
    insert into @Json_Snippets (id, json) VALUES (1, '{"root":{"obj":"two"}}');

   select
          JSON_QUERY(js.json) as 'dont_want_this'
   from
        @Json_Snippets js
    FOR JSON PATH;

END

我必须使用 JSON_QUERY 以避免在 json 列中转义字符,即 json 字符串保持为 json。运行上面给出:
[{"dont_want_this":{"root":{"obj":"one"}}},{"dont_want_this":{"root":{"obj":"two"}}}]

我想得到的是:
[{"root":{"obj":"one"}},{"root":{"obj":"two"}}]

最佳答案

如果我理解正确,下一种方法可能会有所帮助。只需选择您的 json数据与 OPENJSON()WITH子句,然后用 FOR JSON 格式化结果:

-- Table
declare @Json_Snippets table (id int, json nvarchar(max));
insert into @Json_Snippets (id, json) VALUES (1, '{"root":{"obj":"one"}}');
insert into @Json_Snippets (id, json) VALUES (1, '{"root":{"obj":"two"}}');

-- Statement
SELECT j.[root]
FROM @Json_Snippets t
CROSS APPLY OPENJSON(t.json, '$') WITH ([root] nvarchar(max) AS JSON) j
FOR JSON AUTO

输出:
[{"root":{"obj":"one"}},{"root":{"obj":"two"}}]

关于sql - 我可以在没有源列名成为 SQL Server 2016 键的情况下使用 FOR JSON 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55742902/

相关文章:

Oracle 中的 SQL 路由查找器 - 递归?

SQL WHERE 多对多或多对多空

ios - 在 Swift 中使用可编码扩展更新对象属性

php - Laravel 5.1 - 表格的拆分内容

php - 如何将 Excel 电子表格中的字段自动填充到 Web 数据库中

android - 使用房间架构为嵌套的 JSON 对象创建表

json - dart中的NosuchMethod用于JSON.decode

c# - 替换多个字段中的多个特殊字符 SQL

sql-server - 使用 PostgreSQL 外部数据包装器从 SQL Server 查询数据时的数据量问题

sql - 如何删除 SQL Server 中的多行