1

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
2
  • Will each key have the same number of values in their arrays?
    – griv
    Commented Jan 2, 2023 at 1:36
  • 1
    @griv yes it will
    – Den. A.
    Commented Jan 2, 2023 at 1:37

2 Answers 2

2

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.

1

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

3
  • Interesting answer. What tool are you using to visualize/calculate the batch?
    – griv
    Commented Jan 2, 2023 at 6:41
  • @griv In SS Management Studio, just click on the toolbar button [Display Estimated Execution Plan] or Cntrl+L Commented Jan 2, 2023 at 18:54
  • 1
    I forgot about this feature. Thanks! @John
    – griv
    Commented Jan 2, 2023 at 19:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.