我已经在下面创建了函数ParseJson
:
create function ParseJson(
@json nvarchar(max))
returns @tempTable table (topKey nvarchar(max), [Key] nvarchar(max), [Value] nvarchar(max))
as
begin
insert
@tempTable
select
x.[key] topKey
, y.[key]
, y.[value]
from openjson(@json) x
cross apply openjson(x.[value]) y
return
end
-- execute
select * from ParseJson(@json)
我定义了一个变量@json
,它不是数组字符串:
set @json =
N'{
"Chapter":
{
"Section":"1.1"
, "Title":"Hello world."
}
}'
然后我执行查询,我将得到结果:
如果我重置变量@json
,它是一个数组字符串:
declare @json nvarchar(max)
set @json =
N'{
"Chapter":[
{
"Section":"1.1"
, "Title":"Hello world."
}
,
{
"Section":"1.2"
, "Title":"Be happy."
}
]
}'
我希望我能得到以下结果:
我不知道我期望的结果是否合理?
如何调整功能以满足期望?
答案 0 :(得分:1)
如果我正确理解了您的问题,那么下一个陈述是获得结果的一种可能方法。该示例显示了如何获取数组键和值(我添加了附加的Something
键)。您需要再添加一个CROSS APPLY
。
DECLARE @json nvarchar(max)
SET @json =
N'{
"Chapter":[
{
"Section":"1.1",
"Title":"Hello world.",
"Something":"Something value"
}
,
{
"Section":"1.2",
"Title":"Be happy."
}
]
}'
SELECT
x.[key] topKey,
z.[key],
z.[value]
FROM OPENJSON(@json) x
CROSS APPLY (SELECT * FROM OPENJSON(x.[value])) y
CROSS APPLY (SELECT * FROM OPENJSON(y.[value])) z
输出:
topKey key value
Chapter Section 1.1
Chapter Title Hello world.
Chapter Something Something value
Chapter Section 1.2
Chapter Title Be happy.
更新:
如果您的JSON具有不同类型的嵌套对象,则方法将有所不同:
DECLARE @json nvarchar(max)
set @json = N'{
"Chapter": [
{
"Section":"1.1",
"Title":"Hello world.",
"Something":"Something value"
},
{
"Section":"1.2",
"Title":"Be happy."
}
],
"Author": { "name":"Annie" , "sex":"Female" }
}'
SELECT
x.[key] topKey,
z.[key] [Key],
z.[value] AS [Value]
FROM OPENJSON(@json) x
CROSS APPLY (SELECT * FROM OPENJSON(x.[value])) y
CROSS APPLY (SELECT * FROM OPENJSON(y.[value])) z
WHERE y.[type] = 5
UNION ALL
SELECT
x.[key] topKey,
y.[key] [Key],
y.[value] AS [Value]
FROM OPENJSON(@json) x
CROSS APPLY (SELECT * FROM OPENJSON(x.[value])) y
WHERE y.[type] <> 5
输出:
topKey Key Value
Chapter Section 1.1
Chapter Title Hello world.
Chapter Something Something value
Chapter Section 1.2
Chapter Title Be happy.
Author name Annie
Author sex Female