Jump to content
IElite

Reading, Modifying, and writing JSON

Recommended Posts

I use the following snippets below to read a JSON file of data:

 

As you can see, in my UpdateContent method, I have access to the fPresidents data structure - after reading in the JSON file in the InitializeForm event  (e.g. FHttp.Get('res\presidents.json'); )

 

QUESTION:

 

Is it possible to make modifications to the JSON file and then write it back out?  (e.g.  FHttp.Put('res\presidents.json') ); ?

 

If not, what are my alternatives?

uses 
... SmartCL.Inet, ECMA.JSON;


  TfrmNavigation = class(TW3Form)
    procedure frmNavigationActivate(Sender: TObject);
  private
    {$I 'Navigation:intf'}
    FHttp: TW3HttpRequest;
    fPresidents: Variant;
    fJSONStr: String;
  protected
    procedure HandleHttpDataReady(Sender:TW3HttpRequest);
    procedure InitializeForm; override;
    procedure InitializeObject; override;
  public
    procedure UpdateContent;
  end;


procedure TfrmNavigation.InitializeObject;
begin
  inherited;
  {$I 'Navigation:impl'}
  ...
  FHttp := TW3HttpRequest.Create;
  FHttp.OnDataReady:= HandleHttpDataReady;
end;


procedure TfrmNavigation.InitializeForm;
begin
  inherited;
  ...
  FHttp.Get('res\presidents.json');
end;


procedure TfrmNavigation.HandleHttpDataReady(Sender:TW3HttpRequest);
begin
  fJSONStr:= Sender.ResponseText;
  asm
   @fPresidents = JSON.parse(@fJSONStr);
  end;
  UpdateContent;
  ...
end;


procedure TfrmNavigation.UpdateContent;
begin
 fScroll.Content.InnerHTML:= '<div>' +
  '<h2><center>' + fPresidents.presidents[fIndex].rank + '</center></h2><br>' +
  '<h2><center>' + fPresidents.presidents[fIndex].name + '</center></h2><br>' +
  '<h3><center>' + fPresidents.presidents[fIndex].dates + '</center></h3><br>' +
  '<center> <img src="' + 'res\' + intToStr(fIndex + 1) + '.jpg' +
             '" alt="image" height="150" width="150" style="border:5px solid red"> </center><br>' +
  '<p>' + fPresidents.presidents[fIndex].notes + '</p>' +
  '</div>';
end;

Share this post


Link to post
Share on other sites

In priciple you can't write to the normal filesystem through the browser.

 

If you want to do that, then either go client/server or use LocalStorage.

 

A server program (node, php etc) can write files and of course your server can be local.

Or if you intend to do this per user you can use local or session storage

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×