1

Is it possible to output a nested array into a table?

I intend to loop over the orders array and capture the line_item id's for the current iteration.

SQL

DECLARE @json NVARCHAR(4000) = N'
{
  "orders":[
    {
      "id":123,
      "line_items":[
        {
          "id":1
        },
        {
          "id":2
        }
      ]
    }
  ]
};'

SELECT
  [LineId]
FROM OPENJSON (@json, '$.orders.line_items') WITH (
  [LineId] BIGINT '$.id'
);

Desired output

id
1
2
1
  • 1
    If the orders array contains a single object: OPENJSON (@json, '$.orders[0].line_items') Commented Jan 12, 2023 at 15:56

1 Answer 1

1

Here is a working option using a CROSS APPLY to extract the array.

SELECT id = JSON_VALUE(B.Value,'$.id')
 FROM OPENJSON(@json, '$.orders') A
 CROSS APPLY OPENJSON (A.value, '$.line_items') as B

Results

id
1
2
Sign up to request clarification or add additional context in comments.

3 Comments

This is great and seems to be what I need, thank you. Is it possible to filter on the current order.id iteration? e.g where id = 123
Just add ` where JSON_VALUE(A.Value,'$.id') = 123` at the end
Ha. I have been looking at this json so long I forgot how to basic. You're a legend and a gent thank you sir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.