SQL Flow Field Guide

Validate and shred a JSON feed

Check a JSON contract, project typed fields with `OPENJSON`, and preserve parent rows when an array is empty or the payload is invalid.

What you are trying to do

An order integration receives JSON payloads with nested line arrays. Run the self-contained example on SQL Server 2016 or later with database compatibility level 130 or higher.

Work through it

  1. Read the three input payloads. One has two lines, one has an empty array, and one is malformed JSON.
  2. The ISJSON check substitutes an empty object for malformed input so OPENJSON receives valid JSON. This keeps the sample from throwing on that row.
  3. Read the WITH schema as a typed projection. AS JSON carries the nested lines fragment to the second OPENJSON call.
  4. The outer APPLY keeps an order row when its line array is empty. Compare its NULL line columns with the two actual line rows.
  5. Try a missing or wrong-typed property and record the result. Add an explicit rejection or quarantine path before accepting untrusted production payloads.
  6. Review Microsoft's JSON function syntax and the SQL Server version and compatibility requirements. OPENJSON

Check your work

The valid order with two lines returns two rows. The empty-array order remains once with NULL line fields. The malformed row remains visible with NULL projected values and does not make the query fail.

Practice SQL

Open in SQL Flow
;WITH Incoming AS (
    SELECT BatchId, Payload
    FROM (VALUES
        (1, N'{"orderId":101,"region":"North","lines":[{"sku":"PEN","quantity":2},{"sku":"PAD","quantity":1}]}'),
        (2, N'{"orderId":102,"region":"South","lines":[]}'),
        (3, N'{not valid json')
    ) AS v(BatchId, Payload)
)
SELECT i.BatchId, h.OrderId, h.Region, line.Sku, line.Quantity
FROM Incoming AS i
OUTER APPLY OPENJSON(CASE WHEN ISJSON(i.Payload) = 1 THEN i.Payload ELSE N'{}' END)
    WITH (OrderId int '$.orderId', Region nvarchar(20) '$.region', Lines nvarchar(max) '$.lines' AS JSON) AS h
OUTER APPLY OPENJSON(COALESCE(h.Lines, N'[]'))
    WITH (Sku nvarchar(20) '$.sku', Quantity int '$.quantity') AS line
ORDER BY i.BatchId, line.Sku;

Knowledge check

Commands in this lesson

Next lesson Capstone: explain a ticket SLA report