Reputation: 23
JSON input looks like this:
{
"reporting.unit": [ "F-1", "F-2", "F-3"],
"notional.lc": [ 100.1, 140.2, 150.3]
}
Desired Output:
reporting.unit | notional.lc |
---|---|
F-1 | 100.1 |
F-2 | 140.2 |
F-3 | 150.3 |
Note I have upwards of 20 columns and many more elements
I tried:
DECLARE @json nvarchar(max);
SELECT @json = '{
"reporting.unit": [ "F-1", "F-2", "F-3"],
"notional.lc": [ 100.1, 140.2, 150.3]
}';
SELECT *
FROM OPENJSON (@json);
but the result was:
key | value | type |
---|---|---|
reporting.unit | [ "F-1", "F-2", "F-3"] | 4 |
notional.lc | [ 100.1, 140.2, 150.3] | 4 |
Upvotes: 1
Views: 1306
Reputation: 81970
Already +1 on griv's answer ... it was my first thought as well.
However, and just for fun, I wanted to try an alternative which ODDLY enough had a lower batch cost 40% vs 60% (image below)
I should also note that 2016 requires a literal while 2017+ can be an expression
Example
DECLARE @json nvarchar(max);
SELECT @json = '{
"reporting.unit": [ "F-1", "F-2", "F-3"],
"notional.lc": [ 100.1, 140.2, 150.3]
}';
Select ReportingUnit = JSON_VALUE(@json,concat('$."reporting.unit"[',N,']'))
,NotionalLC = JSON_VALUE(@json,concat('$."notional.lc"[',N,']'))
From ( Select Top 25 N=-1+Row_Number() Over (Order By (Select NULL))
From master..spt_values n1
) A
Where JSON_VALUE(@json,concat('$."reporting.unit"[',N,']')) is not null
Results
ReportingUnit NotionalLC
F-1 100.1
F-2 140.2
F-3 150.3
Image
Upvotes: 1
Reputation: 2245
You can use OPENJSON
with multiple JOIN
's to join your columns together using your array keys to get the values in a column/row format.
DECLARE @json nvarchar(max);
SELECT @json = '{
"reporting.unit": [ "F-1", "F-2", "F-3"],
"notional.lc": [ 100.1, 140.2, 150.3]
}';
SELECT
a.value AS [reporting.unit],
b.value AS [notional.lc]
FROM OPENJSON(@json, '$."reporting.unit"') a
JOIN OPENJSON(@json, '$."notional.lc"') b
ON a.[key] = b.[key]
Result:
reporting.unit | notional.lc |
---|---|
F-1 | 100.1 |
F-2 | 140.2 |
F-3 | 150.3 |
Demo here.
Upvotes: 2