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?
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).
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With