SQL Server中用于嵌套json数据的OpenJson?
我有一个json数据,如下所示:SQL Server中用于嵌套json数据的OpenJson?,json,sql-server,open-json,Json,Sql Server,Open Json,我有一个json数据,如下所示: [ {"id": 1}, {"id": 3}, {"id": 2, "children": [{"id": 4}, {"id": 5}]} ] declare @doc nvarchar(max) = N'[{"id":1},{"id":3},{"id":2,"children":[{"id":4},{"id":5}]}]'; with q as ( select [key] nodePath, cast(json_
[
{"id": 1}, {"id": 3}, {"id": 2, "children": [{"id": 4}, {"id": 5}]}
]
declare @doc nvarchar(max) = N'[{"id":1},{"id":3},{"id":2,"children":[{"id":4},{"id":5}]}]';
with q as
(
select [key] nodePath,
cast(json_value(d.[value],'$.id') as int) Id,
cast(null as int) ParentId,
cast(json_query(d.[value],'$.children') as nvarchar(max)) children
from openjson(@doc) d
union all
select q.nodePath + '.' + d.[key] nodePath,
cast(json_value(d.[value],'$.id') as int) Id,
q.id ParentId,
cast(json_query(d.[value],'$.children') as nvarchar(max)) children
from q
outer apply openjson(q.children) d
where q.children is not null
)
select Id, row_number() over (order by nodePath) [Order/Index], ParentId
from q
order by [Order/Index]
请帮助我如何将此数据解析为关系数据:
Column: Id Order/Index ParentId
---------------------------------------
1 1 0
3 2 0
2 3 0
4 4 2
5 5 2
在这个请求中有一些非常重要的事情。首先是按文档位置对结果行进行排序,在使用OPENJSON…WITH投影列时,该位置不可见。第二个是您需要一个分层查询(假设可能有多个级别) 总之,像这样的:
[
{"id": 1}, {"id": 3}, {"id": 2, "children": [{"id": 4}, {"id": 5}]}
]
declare @doc nvarchar(max) = N'[{"id":1},{"id":3},{"id":2,"children":[{"id":4},{"id":5}]}]';
with q as
(
select [key] nodePath,
cast(json_value(d.[value],'$.id') as int) Id,
cast(null as int) ParentId,
cast(json_query(d.[value],'$.children') as nvarchar(max)) children
from openjson(@doc) d
union all
select q.nodePath + '.' + d.[key] nodePath,
cast(json_value(d.[value],'$.id') as int) Id,
q.id ParentId,
cast(json_query(d.[value],'$.children') as nvarchar(max)) children
from q
outer apply openjson(q.children) d
where q.children is not null
)
select Id, row_number() over (order by nodePath) [Order/Index], ParentId
from q
order by [Order/Index]
输出
Id Order/Index ParentId
----------- -------------------- -----------
1 1 NULL
3 2 NULL
2 3 NULL
4 4 2
5 5 2
(5 rows affected)
这是不够的信息。。。是否只有一个对象
子对象
位于第一级,或者是否也有更多更深层的嵌套子对象
?换句话说:id=5
是否可以拥有子项
本身?是的,在本示例中,只有第一级子项,您是对的,在我的项目中有更多级别和嵌套数据惊人,感谢您的支持!