sql-serverjsonpathjson-value

Equivalent of the $[*] jsonpath for SQL Server?


I would like to use a JSON path like $[*].name or $[..].name on a JSON like this one:

[
    {"id": 1, "name": "John"}, 
    {"id": 2, "name": "Mary"}, 
    {"id": 3, "name": "Peter"}
]

To get as result:

["John", "Mary", "Peter"]

But when I try this on SQL Server 2019 using:

SELECT JSON_VALUE(json_data, '$[*].name')
FROM users

I got this error:

JSON path is not properly formatted. Unexpected character '*' is found at position 2.

So how can I get the expected result using a jsonpath compatible with SQL Server?


Solution

  • Something like this.

    SQL

    -- DDL and sample data population, start
    DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, json_data NVARCHAR(MAX));
    INSERT @tbl (json_data) VALUES 
    ('[{"id": 1, "name": "John"}, {"id": 2, "name": "Mary"}, {"id": 3, "name": "Peter"}]'),
    ('[{"id": 1, "name": "Sunny"}, {"id": 2, "name": "Paul"}, {"id": 3, "name": "Michael"}]');
    -- DDL and sample data population, end
    
    SELECT ID, result = '[' + STRING_AGG(QUOTENAME(JSON_VALUE(j.value, '$.name'),CHAR(34)), ',') + ']'
    FROM @tbl
    CROSS APPLY OPENJSON(json_data, '$') AS j
    GROUP BY ID;
    

    Output

    ID result
    1 ["John","Mary","Peter"]
    2 ["Sunny","Paul","Michael"]