[英]SQL JSON query to extract an object
I think the problem is because I have hard brackets [] in the 'groups' object.我认为问题是因为我在“组”object 中有硬括号 []。
JSON: JSON:
declare @json nvarchar(max) = N'{ "agents": [ {
"id": 9544321,
"uuid":"xxxx-xxx-xxxx",
"groups": [
{
"name": "GROUP NAME HERE",
"id": 123456
}
],
"support": true
}]}'
What I'm trying to get to is:我想要达到的是:
id ![]() |
uuid ![]() |
group name![]() |
group id![]() |
---|---|---|---|
9544321 ![]() |
xxxx-xxx-xxxx ![]() |
GROUP NAME HERE![]() |
123456 ![]() |
And then if there is a second group specified in the 'groups' object that'd be two rows.然后,如果在“组”object 中指定了第二组,那将是两行。 etc
ETC
This is my code so far, but it just leaves the [group name] and [group id] columns blank.到目前为止,这是我的代码,但它只是将 [group name] 和 [group id] 列留空。 I've also tried a cross apply and that didn't work (same result).
我也尝试过交叉应用,但没有奏效(结果相同)。
select *
from openjson(@json, '$.agents')
with (
id int '$.id',
uuid varchar(60) '$.uuid',
groups nvarchar(max) '$.groups' as json
)
outer apply openjson (groups)
with ([group name] nvarchar(max) '$',
[group id] int '$'
)
Try this:尝试这个:
select *
from openjson(@json, '$.agents')
with (
id int '$.id',
uuid varchar(60) '$.uuid',
groups nvarchar(max) '$.groups' as json
)
outer apply openjson (groups, '$')
with ([name] nvarchar(max),
[id] int
)
Did you find the difference?你发现区别了吗? You have placed the value 'Group Name' which is the value, instead of keys in json.
您已将值“组名”放置在 json 中,而不是键。
@BeckyG , you're almost there. @BeckyG ,你快到了。 Please, pay attention to lines 29 and 30:
请注意第 29 和 30 行:
DECLARE @json NVARCHAR(MAX) = N'{ "agents": [ {
"id": 9544321,
"uuid":"xxxx-xxx-xxxx",
"groups": [
{
"name": "GROUP NAME HERE",
"id": 123456
},
{
"name": "GROUP NAME HERE 2",
"id": 1234567
}
],
"support": true
}]}';
SELECT agents.id,
agents.uuid,
groups.name [group name],
groups.id [group id]
FROM OPENJSON(@json, '$.agents')
WITH (
id INT '$.id',
uuid VARCHAR(60) '$.uuid',
groups NVARCHAR(MAX) '$.groups' AS JSON
) AS agents
OUTER APPLY OPENJSON (agents.groups)
WITH (
[name] NVARCHAR(MAX) '$.name',
[id] INT '$.id'
) AS groups;
Happy coding!快乐编码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.