How to parse nested JSON array using SQL Server

后端 未结 2 1555
孤城傲影
孤城傲影 2021-02-13 11:02

I am currently able to parse most of a JSON file using SQL Server\'s \"OPENJSON WITH (...\" syntax. However, this particular file contains nested arrays which I do not know how

2条回答
  •  广开言路
    2021-02-13 11:37

    I just had the same problem, and I ended up solving it with multiple CROSS APPLY clauses.

    Here's an example of my JSON:

    DECLARE @PermsJSON NVARCHAR(MAX) =
    N'[{
        "AppId": 1,
        "Perms":
        [{
    
            "Permission": ["AA", "BB"],
            "PermissionTypeID": 2
        },
        {
            "Permission": ["10"],
            "PermissionTypeID": 1
        }]
    },
    {
        "AppId": 2,
        "Perms":
        [{
    
            "Permission": ["IM", "NM"],
            "PermissionTypeID": 2
        },
        {
            "Permission": ["42"],
            "PermissionTypeID": 1
        }]
    }]';
    

    And then I can parse it using the following query:

    SELECT
        a.AppId
        ,[Permission] = c.Value
        ,b.PermissionTypeID
    FROM
        OPENJSON(@PermsJSON)
        WITH
            (
                AppId INT N'$.AppId'
                ,Perms NVARCHAR(MAX) AS JSON
            ) AS a
    CROSS APPLY
        OPENJSON(a.Perms)
        WITH
            (
                PermissionTypeID INT
                ,[Permission] NVARCHAR(MAX) AS JSON
            ) AS b
    CROSS APPLY OPENJSON(b.Permission) AS c;
    

    The results then look like this:

    AppId   Permission  PermissionTypeID
    1       AA          2
    1       BB          2
    1       10          1
    2       IM          2
    2       NM          2
    2       42          1
    

提交回复
热议问题