3

For a minimal working example say I have a column storing JSON with a structure similar to the following.

DECLARE @json NVARCHAR(4000) = 
 '{"Dims": 
 [
 {"Name":"Apple", "Baking": ["Pie","Tart"], "Plant":"Tree"},
 {"Name":"Tomato", "Cooking":["Stew","Sauce"], "Plant":"Vine"},
 {"Name":"Banana","Baking":["Bread"], "Cooking":["Fried"], "Plant":"Arborescent"}
 ]}
'

This is valid JSON and scalars can be returned.

SELECT ISJSON(@json);
1
SELECT JSON_VALUE(@json,'$.Dims[0].Name');
Apple

However, when I use JSON_QUERY to return the names of all of the "Dims" SQL Server 2017 errors.

SELECT JSON_QUERY(@json,'$.Dims[*].Name');
Msg 13607, Level 16, State 4, Line 16
JSON path is not properly formatted. Unexpected character '*' is found at position 7.

This should return

["Apple", "Tomato", "Banana"]

This is a valid standard JSON path. Any ideas why this is not working and how to get this to work on SQL Server 2017.

asked Jan 21, 2019 at 22:36

1 Answer 1

2

Looks like that is not currently supported, and would make a good feedback item.

You can get the names into a resultset with a query like:

select json_value(v.value,'$.Name') Name
from openjson(@json,'$.Dims') v

And from there you can construct a new JSON doc, but if you want an array of primitives, you need to do something like this.

select concat('[',string_agg( quotename(json_value(v.value,'$.Name'), '"'), ', ') WITHIN GROUP ( ORDER BY [key] ) ,']')
from openjson(@json,'$.Dims') v

I don't think there is a way to get an array of primitive values (ie not objects) with FOR JSON queries.

answered Jan 21, 2019 at 23:25
2
  • An suggestion has been posted on Microsoft's site (908035). Commented Jan 22, 2019 at 12:53
  • 1
    Thanks for the workaround. The pattern is to select the path down to the items with OPENJSON and then JSON_VALUE on the each item to extract the value. Commented Jan 22, 2019 at 13:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.