我有一个 SQL Server 脚本的代码摘录,它读取 JSON 文件并插入到表中。我被文件的一部分困住了,它是一个数组。例子:
"top": 19.2743, "bottom": 20.3115, "left": 0.2878, "right": 1.7038, "isInternalToDevice": false, "numberOfLegs": 3, "legs": [ 3, 2 ],
我正在尝试将“腿”作为“3,2”
这是读取其他所有内容的代码 - 只需要腿(站立:-))
DECLARE @JSONRoot VARCHAR(50) SET @JSONRoot = '$._embedded.symbols' SELECT [id], [description], [displayCategoryProgrammaticName], [displayCategoryProgrammaticNameDisplay], [manufacturer], [model], [modelqualifier], [ProgrammaticName], [Type], [Position], [Label], [ReceptacleType], [ConnectorType], [NumberOfLegs] FROM OPENROWSET (BULK 'D:\Test\TestFileSymbols.json', SINGLE_CLOB) as j CROSS APPLY OPENJSON(BulkColumn, ''+@JSONRoot+'') WITH ( [id] UNIQUEIDENTIFIER, [description] VARCHAR(200), [displayCategoryProgrammaticName] VARCHAR(50), [displayCategoryProgrammaticNameDisplay] VARCHAR(50), [manufacturer] VARCHAR(100), [model] VARCHAR(100), [modelqualifier] VARCHAR(100), [openings] NVARCHAR(MAX)'$.openings' AS JSON ) OUTER APPLY OPENJSON(openings) WITH ( [ProgrammaticName] VARCHAR(100) N'$.programmaticName', [Type] VARCHAR(100) N'$.type', [Position] VARCHAR(100) N'$.side', [Label] VARCHAR(30) N'$.label', [ReceptacleType] VARCHAR(100) N'$.receptacleType', [ConnectorType] VARCHAR(50) N'$.connectorType', [NumberOfLegs] INT N'$.numberOfLegs', JSON_QUERY([openings], N'$.legs') AS Legs )
您需要$.legs使用该AS JSON选项返回,然后您可以进一步查询,如果需要,通过 将其转换为逗号分隔的字符串STRING_AGG(),例如:
$.legs
AS JSON
STRING_AGG()
declare @json nvarchar(max) = N'{ "top": 19.2743, "bottom": 20.3115, "left": 0.2878, "right": 1.7038, "isInternalToDevice": false, "numberOfLegs": 3, "legs": [ 3, 2 ] }'; select * from openjson(@json) with ( [NumberOfLegs] int N'$.numberOfLegs', [Legs] nvarchar(max) N'$.legs' as JSON ) shredded outer apply ( select string_agg(value, ',') from openjson(Legs) ) joined(Leggy);
返回结果: