how to add element in json object

You can add an element to a JSON object in Delphi by using the TJSONObject class provided by the System.JSON unit. Here's an example:


  MyObject: TJSONObject;
  MyObject := TJSONObject.Create;

  // Add a string element
  MyObject.AddPair('name', 'John');

  // Add an integer element
  MyObject.AddPair('age', TJSONNumber.Create(25));

  // Add a boolean element
  MyObject.AddPair('isStudent', TJSONBool.Create(True));

  // Add a nested JSON object
  var AddressObject := TJSONObject.Create;
  AddressObject.AddPair('street', '123 Main St');
  AddressObject.AddPair('city', 'New York');
  MyObject.AddPair('address', AddressObject);

  // Add an array element
  var HobbiesArray := TJSONArray.Create;
  MyObject.AddPair('hobbies', HobbiesArray);

  // Convert the JSON object to a string
  var JsonString := MyObject.ToString;

  // Free the JSON object

In the example above, we create a TJSONObject called MyObject and add various elements to it using the AddPair method. We add a string element with the key "name", an integer element with the key "age", a boolean element with the key "isStudent", a nested JSON object with the key "address", and an array element with the key "hobbies".

After adding the elements, we convert the MyObject JSON object to a string using the ToString method. Finally, we free the MyObject object to release the allocated memory.

Please note that you need to include the System.JSON unit in your uses clause in order to use the TJSONObject, TJSONArray, and other JSON-related classes and methods.