Den. A.
Den. A.

Reputation: 23

Use openjson to get columns from JSON with multiple arrays of elements

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

Answers (2)

John Cappelletti
John Cappelletti

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

enter image description here

Upvotes: 1

griv
griv

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

Related Questions