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
- Read the three input payloads. One has two lines, one has an empty array, and one is malformed JSON.
- The
ISJSONcheck substitutes an empty object for malformed input soOPENJSONreceives valid JSON. This keeps the sample from throwing on that row. - Read the
WITHschema as a typed projection.AS JSONcarries the nested lines fragment to the secondOPENJSONcall. - The outer APPLY keeps an order row when its line array is empty. Compare its NULL line columns with the two actual line rows.
- Try a missing or wrong-typed property and record the result. Add an explicit rejection or quarantine path before accepting untrusted production payloads.
- 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