Search code examples
jsondelphidelphi-7

Insert new field to JSON file


How can I insert or add a new Field to JSON file ? I'm using lkjson btw.

var
  js: TlkJSONobject;
  val : String;
begin
  js := TlkJSONstreamed.loadfromfile(jsonFile) as TlkJsonObject;
  try
    try
      val := js.Field['users'].Field[username].Field[value5].Value; //field value5 doesnt exist
    except
      //add field

    end;
    TlkJSONstreamed.SaveToFile(js, jsonFile);
  finally
    js.Free;
  end;
end;

Solution

  • Like this:

    (js.Field['users'].Field[username] as TlkJSONobject).Add(value5, '1');
    

    Where users and username do exist.