Lesson 4 of 4 JSON in SQL Databases

Reading and Searching JSON in T-SQL

This lesson explains JSON paths and the functions that extract, test and shred JSON: JSON_VALUE, JSON_QUERY, JSON_PATH_EXISTS, JSON_CONTAINS and OPENJSON.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain JSON path syntax and lax and strict modes.
  • Distinguish between JSON_VALUE, JSON_QUERY, JSON_PATH_EXISTS and JSON_CONTAINS.
  • Describe how OPENJSON with a WITH clause shreds arrays into typed rows.

JSON paths

A JSON path starts at $, the whole document, and navigates with .property and [index], such as $.lines[0].qty; [*] refers to every array element in functions that support it, such as JSON_CONTAINS. Property names with spaces or special characters are quoted: $."unit price". In the default lax mode, a missing path returns NULL; in strict mode ('strict $.qty') it raises an error, which helps catch unexpected payloads.

Scenario questions

Lax and strict paths

Exam skills 1.3.3

Choose the path mode or syntax for each requirement.

Log in to try this activity Interactive activities are free with an account.

Scalar and fragment extraction

JSON_VALUE(doc, path) returns a scalar as nvarchar(4000), or as another type with RETURNING; it returns NULL in lax mode when the path points to an object or array. JSON_QUERY(doc, path) returns an object or array fragment. JSON_PATH_EXISTS(doc, path) returns 1 when a path exists, even when its value is null. JSON_CONTAINS(doc, value, path) returns 1 when the value is found at the path, 0 when not, and NULL when an argument is NULL or the path does not exist; for strings, a fourth argument of 1 uses LIKE semantics.

DECLARE @j json = N'{"order":{"id":17,"lines":[{"sku":"TNT-2P","qty":1},{"sku":"STV-01","qty":2}]},"tags":["camp","summer"]}';

SELECT JSON_VALUE(@j, '$.order.id' RETURNING int)   AS OrderId,      -- 17
       JSON_QUERY(@j, '$.order.lines')               AS LinesArray,   -- the array fragment
       JSON_PATH_EXISTS(@j, '$.order.coupon')        AS HasCoupon,    -- 0
       JSON_CONTAINS(@j, 'summer', '$.tags[*]')      AS IsSummer;     -- 1
Match the pairs

JSON functions

Exam skills 1.3.3

Match each function with what it returns.

Log in to try this activity Interactive activities are free with an account.

Shredding with OPENJSON

OPENJSON is a table-valued function that turns JSON into rows. Without a schema it returns key, value and type columns for each property or element. With a WITH clause it returns typed columns mapped by paths, and AS JSON keeps a nested object or array as JSON for further shredding with CROSS APPLY. This is how JSON arrays sent by applications, or returned by language models, become rows that can be inserted or joined.

SELECT l.sku, l.qty
FROM OPENJSON(@j, '$.order.lines')
     WITH (sku varchar(20) '$.sku',
           qty int         '$.qty') AS l;

The following diagram turns a JSON array into rows.

Shredding JSON with OPENJSON. A JSON document, such as an order with an array of lines, is passed to OPENJSON with a path to the array and a WITH clause that maps properties to typed columns. Each array element becomes a row, ready to insert or join. A nested object or array can be returned AS JSON and shredded further with CROSS APPLY.
Each array element becomes one typed row.
Worked example

Importing an order array

A procedure receives a parameter @orders json containing an array of orders, each with a nested array of lines. It must insert one row per line with typed columns and reject the payload if any order lacks an id. Which functions should it use?

Use OPENJSON(@orders) WITH (id int 'strict $.id', lines json '$.lines' AS JSON) to produce one row per order, then CROSS APPLY OPENJSON(lines) WITH (...) to produce one row per line, and insert the result. Strict mode on $.id raises an error for orders without an id instead of silently inserting NULL. JSON_VALUE with indexes such as $[0] would only read fixed positions and cannot iterate an array of unknown length.

Check yourself

What does JSON_VALUE return in lax mode when the path points to an object?

Show answer

NULL, because JSON_VALUE returns scalars only; JSON_QUERY returns objects and arrays.

Exam Tips

Remember for the exam

  • Scalar: JSON_VALUE; object or array: JSON_QUERY.
  • Array of unknown length into rows: OPENJSON with a WITH clause.
  • Value somewhere in an array: JSON_CONTAINS with [*].
  • Missing paths: lax mode returns NULL, strict mode raises an error.