Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search json array using SQL server JSON_VALUE

Assuming a given json object:

{"info":{"address":[{"town":"Belgrade"},{"town":"Paris"},{"town":"Madrid"}]}}

SQL server has JSON_VALUE function that can be used in WHERE clause to match against a particular json element e.g.

WHERE JSON_VALUE(columnName, $.info.address[1].town) = 'Belgrade'

The issue is that it requires an index. How do I search in all array elements specified by the path?

like image 211
tunafish24 Avatar asked Apr 10 '19 09:04

tunafish24


People also ask

How do I query JSON data in SQL Server?

To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).

How can I get specific data from JSON?

Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.

What is the difference between the Json_value and Json_query functions?

The key difference between JSON_VALUE and JSON_QUERY is that JSON_VALUE returns a scalar value, while JSON_QUERY returns an object or an array.

How do I find the length of a JSON array in SQL Server?

To obtain the size of a JSON-encoded array or object, use the json_size function, and specify the column containing the JSON string and the JSONPath expression to the array or object.


1 Answers

You may try to use OPENJSON and a WITH clause (to specify columns and their types), and then search in all elements:

-- JSON
DECLARE @json nvarchar(max)
SET @json = N'{"info":{"address":[{"town":"Belgrade"},{"town":"Paris"},{"town":"Madrid"}]}}'

-- Statement
SELECT Town
FROM OPENJSON(@json, '$.info.address') WITH (
   Town nvarchar(100) '$.town'
)
WHERE Town = N'Belgrade'

If the JSON content is stored in a table column, next approach is also an option:

-- Table
CREATE TABLE #Data (
   Id int,
   JsonData varchar(max)
)
INSERT INTO #Data
   (Id, JsonData)
VALUES 
   (1, N'{"info":{"address":[{"town":"Belgrade"},{"town":"Paris"},{"town":"Madrid"}]}}'),
   (2, N'{"info":{"address":[{"town":"Belgrade"},{"town":"Paris"},{"town":"Madrid"}]}}'),
   (3, N'{"info":{"address":[{"town":"Belgrade"},{"town":"Paris"},{"town":"Madrid"}]}}')

-- Statement
SELECT DISTINCT d.Id
FROM #Data d
CROSS APPLY OPENJSON(d.JsonData, '$.info.address') WITH (
   Town nvarchar(100) '$.town'
) j   
WHERE (j.Town = N'Belgrade') OR (j.Town = N'Paris')

Result:

-------
Id
-------
1
2
3
like image 82
Zhorov Avatar answered Sep 19 '22 21:09

Zhorov