I took the idea from this answer and got further questions. I defined a variable:
declare @json nvarchar(max)
set @json =
N'{
"Book":{
"IssueDate":"02-15-2019"
, "Detail":{
"Type":"Any Type"
, "Author":{
"Name":"Annie"
, "Sex":"Female"
}
}
, "Chapter":[
{
"Section":"1.1"
, "Title":"Hello world."
}
,
{
"Section":"1.2"
, "Title":"Be happy."
}
]
, "Sponsor":["A","B","C"]
}
}'
Then I execute the query:
select
x.[key] topKey
, y.[key]
, y.[value]
, '{"'+ y.[key] + '":' + y.[value] +'}' jsonString
from openjson(@json) x
cross apply openjson(x.[value]) y
I reset the variable @json
from the table(namely jsonString
), and execute the query above repeatedly.
The following is the result of execution:
I've been trying to store the result above into a single table and had created the function below:
create function ParseJson(
@parent nvarchar(max), @json nvarchar(max))
returns @tempTable table (topKey nvarchar(max), FieldName nvarchar(max), FieldValue nvarchar(max), IsType int)
as
begin
; with cte as (
select
x.[key] topKey,
y.[key] FieldName,
y.[value] FieldValue
, iif([dbo].GetTypeId(y.[Key]) is null or y.[Key] = 'Type' ,0 ,1) IsType
from
openjson(@json) x
cross apply openjson(x.[value]) y
)
insert
@tempTable
select
x.*
from
cte x
union all
select
z.*
from
cte y
cross apply ParseJson(default,'{"'+ y.FieldName + '":' + y.FieldValue+'}') z
where y.IsType=1
return
end
-- execute
select * from ParseJson(default, @json)
The field IsType
is the condition to check if recursion is needed.
[dbo].GetTypeId
is a user defined function which is for checking whether FieldValue
is a terminal value although it might not look like something for that purpose.
The following is the function GetTypeId
and the Type
table:
create function GetTypeId(
@typeName nvarchar(255)
)
returns nvarchar(1000)
as
begin
declare
@typeId nvarchar(1000)
select
@typeId=id
from
[Type]
where
[Type].[Name]=@typeName
return @typeId
end
go
Here is the error message :
The JSON text format is incorrect. Unexpected character '0' was found at position 13.