How to parse JSON string recursively with openjson

后端 未结 1 1438
一向
一向 2021-01-28 05:18

I have the following JSON data :

set @json = N\'{
    \"Book\":{
        \"IssueDate\":\"02-15-2019\"
        , \"Detail\":{
            \"Type\":\"Any Type\"
           


        
1条回答
  •  醉话见心
    2021-01-28 05:56

    I'm not sure if your expectation of the results is reasonable but clearly the returning table of your function doesn't match what you stated -- it lacks topKey column. For this reason, I'd rather aggregate the path of the hierarchy. Here we go:

    create function ParseJson(
        @parent nvarchar(max), @json nvarchar(max))
    returns @tempTable table (
        [key] nvarchar(max), [value] nvarchar(max))
    as
    begin
        ; with cte as (
            select 
                iif(@parent is null, [key]
                    , concat(@parent, '.', [key])) [key]
                , [value]
            from 
                openjson(@json)
        )
        insert 
            @tempTable
        select 
            x.* 
        from 
            cte x
        union all
        select 
            x.* 
        from 
            cte y
        cross apply ParseJson(y.[key], y.[value]) x
        where isjson(y.[value])=1
    
        return
    end
    

    And the results:

    0 讨论(0)
提交回复
热议问题