Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I loop through a json array in sql to select a value at a specific index

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
like image 903
Aji K Saine Avatar asked Jul 28 '16 12:07

Aji K Saine


People also ask

How can I get specific data from JSON in SQL?

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 do you loop a JSON array?

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.

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.


1 Answers

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]')
like image 136
M_ Fa Avatar answered Sep 28 '22 11:09

M_ Fa