[英]Reading JSON data with nested obects within arrays to SQL Server 2016
我一直在尝试将以下 JSON 数据读入 SQL Server 2016。我无法从Values
对象返回任何值。
select 语句显示binWidth
、 minVal
、 nBins
和type
NULL 值。
另外,我不确定如何处理结果数组,因为这些值没有分配任何键。
非常感谢任何帮助。
JSON 数据:
DECLARE @json NVARCHAR(MAX) =
'{
"Histograms": [
{
"Name": "20458-Z01-DWL",
"RegisterId": "0",
"Tags": [],
"UUID": "a4c5fa3f-ecb8-4635-8e94-5167e743b518",
"Values": [
{
"config": {
"binWidth": 50,
"minVal": 50,
"nBins": 18,
"type": "total wait"
},
"result": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
]
},
{
"Name": "20458-Z02-DWL",
"RegisterId": "1",
"Tags": [],
"UUID": "95d57826-30f6-44c9-ad0d-6a24684fcaed",
"Values": [
{
"config": {
"binWidth": 50,
"minVal": 50,
"nBins": 18,
"type": "total wait"
},
"result": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
]
},
{
"Name": "20458-Z03-DWL",
"RegisterId": "2",
"Tags": [],
"UUID": "90223a0e-3d1a-471f-a871-ee56da4799f5",
"Values": [
{
"config": {
"binWidth": 50,
"minVal": 50,
"nBins": 18,
"type": "total wait"
},
"result": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
]
},
{
"Name": "20458-Z04-DWL",
"RegisterId": "3",
"Tags": [],
"UUID": "6c837def-feeb-48d5-8dcf-307b56ec44e9",
"Values": [
{
"config": {
"binWidth": 50,
"minVal": 100,
"nBins": 16,
"type": "total wait"
},
"result": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
]
},
{
"Name": "20458-Z05-DWL",
"RegisterId": "4",
"Tags": [],
"UUID": "76bd5aa2-8860-4a2e-997d-3c83e940790f",
"Values": [
{
"config": {
"binWidth": 50,
"minVal": 100,
"nBins": 16,
"type": "total wait"
},
"result": [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
]
}
],
"LogEntryId": 6593,
"StartTimestamp": "2020-07-20T16:05:00Z",
"Timestamp": "2020-07-20T16:06:00Z"
}'
从数据中获取项目的查询:
SELECT
[Name],
[RegisterId],
UUID,
binWidth
minVal,
nBins,
[type]
FROM
OPENJSON (@json, '$.Histograms')
WITH
([Name] nvarchar(100),
[RegisterId] nvarchar(100),
UUID nvarchar(100),
[Values] nvarchar(max) AS json) AS Histograms
CROSS APPLY
OPENJSON (Histograms.[Values])
WITH
(binWidth int,
minVal int,
nBins int,
[type] nvarchar(100)) AS config
想通了最后一个问题。 将结果数组传递到一个字段中 - 在下面编辑。 再次感谢您的指导,学到了很多!
select
Histograms.[Name],
Histograms.[RegisterId],
Histograms.UUID,
config.binWidth,
config.minVal,
config.nBins,
config.[type],
r.[key] as 'result position',
r.[value] as 'result value'
from
openjson(@json, '$.Histograms')
with (
[Name] nvarchar(100),
LogEntryId int,
[RegisterId] nvarchar(100),
UUID nvarchar(100),
[Values] nvarchar(max) as json
) as Histograms
cross apply openjson (Histograms.[Values]) h
cross apply openjson (h.value)
with
(
binWidth int N'$.config.binWidth',
minVal int N'$.config.minVal',
nBins int N'$.config.nBins',
[type] nvarchar(100) N'$.config.type',
result nvarchar(max) as json
) as config
CROSS APPLY OPENJSON(config.result) r
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.