通过OPENJSON检索JSON嵌套值

时间:2019-07-02 20:14:06

标签: sql-server open-json

需要获取击球员/击球员/类型1-4的值

这是JSON数据

[
{
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters":
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" },
                        { "id": "1002", "type": "Chocolate" },
                        { "id": "1003", "type": "Blueberry" },
                        { "id": "1004", "type": "Devil's Food" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5007", "type": "Powdered Sugar" },
                { "id": "5006", "type": "Chocolate with Sprinkles" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    }
]

使用从openjson中选择的*检索值,但无法获取嵌套/嵌套的值

Select * from openjson(@json_known, '$[1]')
with
(
KeyID int '$.id',
[Type] varchar(max) '$.type',
[Name] varchar(max) '$.name',
PPU varchar(max) '$.ppu',
Batter0 varchar(max) '$.batters.batter.type[0]',
Batter1 varchar(max) '$.batters.batter.id[1]',
Batter2 varchar(max) '$.batters.batter.type[2]',
Batter3 varchar(max) '$.batters.batter.type[3]'
)

1 个答案:

答案 0 :(得分:0)

您可以使用:

Select x.Batter
from openjson(@json_known, '$') s
cross apply openjson(json_query(s.value, '$.batters.batter'))
with (id INT '$.id',Batter varchar(max) '$.type') x;

db<>fidlde demo