SQL Server
SQL Server
JSON: Nested Objects
See more JSON Examples
Here we have a JSON object that contains nested JSON objects. This example demonstrates how to access the contents of the nested objects.
{
"name": "donut",
"image":
{
"fname": "donut.jpg",
"w": 200,
"h": 200
},
"thumbnail":
{
"fname": "donutThumb.jpg",
"w": 32,
"h": 32
}
}
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
DECLARE @iTmp0 int
DECLARE @iTmp1 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
-- This is the above JSON with whitespace chars removed (SPACE, TAB, CR, and LF chars).
-- The presence of whitespace chars for pretty-printing makes no difference to the Load
-- method.
DECLARE @jsonStr nvarchar(4000)
SELECT @jsonStr = '{"name": "donut","image":{"fname": "donut.jpg","w": 200,"h": 200},"thumbnail":{"fname": "donutThumb.jpg","w": 32,"h": 32}}'
EXEC sp_OAMethod @json, 'Load', @success OUT, @jsonStr
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @json, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @json
RETURN
END
-- Get the "image" object.
DECLARE @imageObj int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @imageObj OUT
EXEC sp_OAMethod @json, 'ObjectOf2', @success OUT, 'image', @imageObj
EXEC sp_OAMethod @imageObj, 'StringOf', @sTmp0 OUT, 'fname'
EXEC sp_OAMethod @imageObj, 'IntOf', @iTmp0 OUT, 'w'
EXEC sp_OAMethod @imageObj, 'IntOf', @iTmp1 OUT, 'h'
PRINT 'image: fname=' + @sTmp0 + ', width=' + @iTmp0 + ', height=' + @iTmp1
-- Get the "thumbnail" object.
DECLARE @thumbObj int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @thumbObj OUT
EXEC sp_OAMethod @json, 'ObjectOf2', @success OUT, 'thumbnail', @thumbObj
EXEC sp_OAMethod @thumbObj, 'StringOf', @sTmp0 OUT, 'fname'
EXEC sp_OAMethod @thumbObj, 'IntOf', @iTmp0 OUT, 'w'
EXEC sp_OAMethod @thumbObj, 'IntOf', @iTmp1 OUT, 'h'
PRINT 'thumbnail: fname=' + @sTmp0 + ', width=' + @iTmp0 + ', height=' + @iTmp1
EXEC @hr = sp_OADestroy @json
EXEC @hr = sp_OADestroy @imageObj
EXEC @hr = sp_OADestroy @thumbObj
END
GO