liveBook · Manning

Json path expression

As explained in 100 SQL Server Mistakes and How to Avoid Them

A JSON path is an expression that identifies a location within a JSON document, including object properties and array elements.

Mistake: treating a JSON path like an ordinary property name. A path begins with $. for the whole document, then follows object properties and array indexes. Omitting an array index returns NULL, even when the array contains one record. section 3.5

Use JSON paths to move between JSON and relational data:

  • Generate hierarchy with FOR JSON PATH aliases such as Address.Line1. section 3.5
  • Extract a scalar with JSON_VALUE(document, '$.EmployeeAddress[0].EmployeeID'). section 3.5
  • Shred a hierarchy with OPENJSON and map nested nodes through paths in WITH. section 3.5

Updating an employee address

A generated EmployeeAddress array can identify the target row with JSON_VALUE(@EmployeeAddress, '$.EmployeeAddress[0].EmployeeID'), then OPENJSON can return EmployeeID, Line1, City, State, and ZipCode as relational columns. section 3.5

Listing 3.24 Shredding the JSON data into relational values
DECLARE @EmployeeAddress NVARCHAR(MAX) ;

SET @EmployeeAddress = (
   SELECT
         1 AS 'EmployeeID'
       , '5331 Rexford Court' AS 'Address.Line1'
       , 'Montgomery'         AS 'Address.City'
       , 'AL'                 AS 'Address.State'
       , '36116'              AS 'Address.ZipCode'
   FOR JSON PATH, ROOT ('EmployeeAddress')
) ;

SELECT *
FROM OPENJSON(@EmployeeAddress, '$.EmployeeAddress[0]')
WITH (
   EmployeeID SMALLINT,
   Line1 NVARCHAR(64) '$.Address.Line1',
   City NVARCHAR(64) '$.Address.City',
   [State] NCHAR(2) '$.Address.State',
   ZipCode NVARCHAR(10) '$.Address.ZipCode'
) ;

Inspect a complete OPENJSON query that selects an array element and maps nested address properties to typed columns. section 3.5

How 100 SQL Server Mistakes and How to Avoid Them covers it

How deep it goes
Explains root notation, object hierarchy, array indexes, and nested-column mapping, but does not develop broader path syntax.
Examples
Uses an EmployeeAddress array containing employee identity and nested address fields.
What it assumes
Assumes familiarity with JSON documents, SQL queries, tables, and arrays.
What you can do after
Apply JSON paths via JSON_VALUE and OPENJSON to identify records, extract values, and return typed relational columns.
How it connects
Connects JSON path expressions with JSON_VALUE, OPENJSON, FOR JSON PATH, arrays, and relational tables.

Also explained in

Compare how 2 books explain json path expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 SQL Server Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.