Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

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 Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.JsonObject;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  jsonA: TJsonObject;
  jsonB: TJsonObject;

begin
  //  Imagine we have two separate JSON objects.
  jsonA := TJsonObject.Create;
  jsonA.UpdateString('animal','zebra');
  jsonA.UpdateString('colors[0]','white');
  jsonA.UpdateString('colors[1]','black');

  jsonA.EmitCompact := False;
  WriteLn(jsonA.Emit());

  //  jsonA contains:

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

  jsonB := TJsonObject.Create;
  jsonB.UpdateString('type','mammal');
  jsonB.UpdateBool('carnivore',False);

  jsonB.EmitCompact := False;
  WriteLn(jsonB.Emit());

  //  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"
  //    ]
  //  }

  jsonA.AddObjectCopyAt(1,'info',jsonB);

  WriteLn(jsonA.Emit());

  //  The result is this:

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


  jsonA.Free;
  jsonB.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.