使用OPENJSON解析azure sql中的json

问题描述 投票:0回答:1

我正在尝试使用OPENJSON将json文件解析为sql。我有一个看起来像这样的结构:

{
    "definitions": {            
        "Event": {
            "properties": {
                "id": {
                    "type": "string",
                    "description": "System-generated Id"
                },
                "transactionDateTime": {
                    "type": "string",
                    "description": "RFC3339-compliant, system-generated timestamp"
                },
                "Name": {
                    "type": "string",
                    "description": "blah"
                }
        }
    }
}

我正在尝试使用select查询读取type部分中每个项目的properties字段。

drop table if exists #temp;
SELECT * into #temp FROM OPENROWSET (BULK 'C:\swagger.json', SINGLE_CLOB) as j
CROSS APPLY OPENJSON(BulkColumn, '$.definitions.Event.properties');
select * from #temp

这将返回一个表#temp,其中包含一个名为[key]的列,其中包含idDateTimeName。在名为value的相邻列中,存在批量json数据,例如{ "type":"string", "description": "....."}

对于[key]列中的每个项目,我希望有一个与type相邻的列,例如string。我想这样做,而无需将[key]字段名称硬编码到sql查询中。

enter image description here

json tsql azure-sql-database
1个回答
0
投票

我能够找到以下解决方案,首先使用变量导入json,然后调用OPENROWSET来读取json。

DECLARE @json varchar(max);
SELECT @json = BulkColumn FROM OPENROWSET(BULK 'C:\swagger.json', SINGLE_CLOB) as j;

DROP TABLE if exists #temp;
SELECT value INTO #temp FROM OPENJSON(@json, '$.definitions.Event.properties')
© www.soinside.com 2019 - 2024. All rights reserved.