Sample code for 30+ languages & platforms
SQL Server Requires Chilkat v11.0.0+

Insert JSON Object into another JSON Object

See more JSON Examples

Demonstrates how to insert one JSON object into another. Effectively, the JSON object must be copied into the other..

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @sTmp0 nvarchar(4000)
    --  Imagine we have two separate JSON objects.
    DECLARE @jsonA int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @jsonA OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    DECLARE @success int
    EXEC sp_OAMethod @jsonA, 'UpdateString', @success OUT, 'animal', 'zebra'
    EXEC sp_OAMethod @jsonA, 'UpdateString', @success OUT, 'colors[0]', 'white'
    EXEC sp_OAMethod @jsonA, 'UpdateString', @success OUT, 'colors[1]', 'black'

    EXEC sp_OASetProperty @jsonA, 'EmitCompact', 0
    EXEC sp_OAMethod @jsonA, 'Emit', @sTmp0 OUT
    PRINT @sTmp0

    --  jsonA contains:

    --  {
    --    "animal": "zebra",
    --    "colors": [
    --      "white",
    --      "black"
    --    ]
    --  }

    DECLARE @jsonB int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @jsonB OUT

    EXEC sp_OAMethod @jsonB, 'UpdateString', @success OUT, 'type', 'mammal'
    EXEC sp_OAMethod @jsonB, 'UpdateBool', @success OUT, 'carnivore', 0

    EXEC sp_OASetProperty @jsonB, 'EmitCompact', 0
    EXEC sp_OAMethod @jsonB, 'Emit', @sTmp0 OUT
    PRINT @sTmp0

    --  jsonB contains:

    --  {
    --    "type": "mammal",
    --    "carnivore": false
    --  }

    --  Let's say we want to insert jsonB into jsonA to get this:

    --  {
    --    "animal": "zebra",
    --    "info" " {
    --        "type": "mammal",
    --        "carnivore": false
    --  	},
    --    "colors": [
    --      "white",
    --      "black"
    --    ]
    --  }

    EXEC sp_OAMethod @jsonA, 'AddObjectCopyAt', @success OUT, 1, 'info', @jsonB

    EXEC sp_OAMethod @jsonA, 'Emit', @sTmp0 OUT
    PRINT @sTmp0

    --  The result is this:

    --  {
    --    "animal": "zebra",
    --    "info": {
    --      "type": "mammal",
    --      "carnivore": false
    --    },
    --    "colors": [
    --      "white",
    --      "black"
    --    ]
    --  }

    EXEC @hr = sp_OADestroy @jsonA
    EXEC @hr = sp_OADestroy @jsonB


END
GO