I have a stored procedure that query the database and store the result in a Json variable. Now I want to loop through the Json array by index to get a specific value. Can some tell me how to achieve this. Below is my query
DECLARE @json NVARCHAR(Max)
DECLARE @name VARCHAR(50) = 'Name'
SET @json = (select name from getalldataView where
SOUNDEX(name) LIKE SOUNDEX(@name) FOR JSON PATH, ROOT('Names'))
DECLARE @i int = 0
WHILE @i < lengthOFArray
BEGIN
SET @i = @i + 1;
SELECT value
FROM OPENJSON(@json, '$.Names[',@i,']');
END
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).
To loop through a JSON array with JavaScript, we can use a for of loop. to loop through the json array with a for of loop. We assign the entry being looped through to obj . Then we get the value of the id property of the object in the loop and log it.
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.
source Here
sample data
{ "type": "MultiPolygon",
"coordinates": [
[
[[40, 40], [20, 45], [45, 30], [40, 40]]
],
[
[[20, 35], [10, 30], [10, 10], [30, 5], [45, 20], [20, 35]],
[[30, 20], [20, 15], [20, 25], [30, 20]]
]
]
}
Sql Code
SELECT polygons.[key] as polygon, lines.[key] as line, x, y
FROM OPENJSON(@multipolygon, '$.coordinates') as polygons
CROSS APPLY OPENJSON(polygons.value) as lines
CROSS APPLY OPENJSON(lines.value)
WITH (x float '$[0]', y float '$[1]')
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