SQL Server
SQL Server
Get the Root of a JSON Document
See more JSON Examples
Demonstrates how to get back to the JSON root object from anywhere in the JSON document. This example uses the following JSON document:
{
"flower": "tulip",
"abc":
{
"x": [
{ "a" : 1 },
{ "b1" : 100, "b2" : 200 },
{ "c" : 3 }
],
"y": 200,
"z": 200
}
}
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
-- 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 = '{"flower": "tulip","abc":{"x": [{ "a" : 1 },{ "b1" : 100, "b2" : 200 },{ "c" : 3 }],"y": 200,"z": 200}}'
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 "abc" object.
DECLARE @abcObj int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @abcObj OUT
EXEC sp_OAMethod @json, 'ObjectOf2', @success OUT, 'abc', @abcObj
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @json, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @json
EXEC @hr = sp_OADestroy @abcObj
RETURN
END
-- Side note: The JSON of a sub-part of the document can be emitted from any JSON object:
EXEC sp_OASetProperty @abcObj, 'EmitCompact', 0
EXEC sp_OAMethod @abcObj, 'Emit', @sTmp0 OUT
PRINT @sTmp0
-- Navigate to the "x" array
DECLARE @xArray int
EXEC @hr = sp_OACreate 'Chilkat.JsonArray', @xArray OUT
EXEC sp_OAMethod @abcObj, 'ArrayOf2', @success OUT, 'x', @xArray
-- Navigate to the 2nd object contained within the array. This contains members b1 and b2
DECLARE @bObj int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @bObj OUT
EXEC sp_OAMethod @xArray, 'ObjectAt2', @success OUT, 1, @bObj
-- Show that we're at "b1/b2".
-- The value of "b1" should be "200"
EXEC sp_OAMethod @bObj, 'IntOf', @iTmp0 OUT, 'b2'
PRINT 'b2 = ' + @iTmp0
-- Now go back to the JSON doc root:
DECLARE @docRoot int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @docRoot OUT
EXEC sp_OAMethod @bObj, 'GetDocRoot2', @success OUT, @docRoot
-- We'll skip the null check and assume it's non-null...
-- Pretty-print the JSON doc from the root to show that this is indeed the root.
EXEC sp_OASetProperty @docRoot, 'EmitCompact', 0
EXEC sp_OAMethod @docRoot, 'Emit', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @json
EXEC @hr = sp_OADestroy @abcObj
EXEC @hr = sp_OADestroy @xArray
EXEC @hr = sp_OADestroy @bObj
EXEC @hr = sp_OADestroy @docRoot
END
GO