SQL Server
SQL Server
JSON Iterate Members
See more JSON Examples
Demonstrates how to loop over the immediate members of a JSON object.Chilkat SQL Server Downloads
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
DECLARE @hr int
-- Important: Do not use nvarchar(max). See the warning about using nvarchar(max).
DECLARE @sTmp0 nvarchar(4000)
DECLARE @success int
SELECT @success = 0
DECLARE @json int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @json OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
DECLARE @jsonStr nvarchar(4000)
SELECT @jsonStr = '{ "id": 1, "name": "A green door", "tags": ["home", "green"], "price": 125 }'
EXEC sp_OAMethod @json, 'Load', @success OUT, @jsonStr
IF @success <> 1
BEGIN
EXEC sp_OAGetProperty @json, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @json
RETURN
END
DECLARE @numMembers int
EXEC sp_OAGetProperty @json, 'Size', @numMembers OUT
DECLARE @i int
SELECT @i = 0
WHILE @i <= @numMembers - 1
BEGIN
DECLARE @name nvarchar(4000)
EXEC sp_OAMethod @json, 'NameAt', @name OUT, @i
DECLARE @value nvarchar(4000)
EXEC sp_OAMethod @json, 'StringAt', @value OUT, @i
PRINT @name + ': ' + @value
DECLARE @iValue int
EXEC sp_OAMethod @json, 'IntAt', @iValue OUT, @i
PRINT @name + ' as integer: ' + @iValue
SELECT @i = @i + 1
END
-- Note: The StringAt method returns the value as a string regardless of the type.
-- If the value is a JSON array (such as for ["home", "green"]), then the JSON encoding
-- of the entire array is returned.
-- The IntAt method returns the value as an integer. If the value does not convert to
-- an integer, then 0 is returned
EXEC @hr = sp_OADestroy @json
END
GO