Search code examples
jsonlazarusfreepascaldelphi

Passing value of JSON data to Free Pascal variable


I'm trying to put together a small program in Free Pascal that gets current exchange rates from Fixer.io in JSON format and uses them to do simple currency conversion. I've got as far as the following, which downloads the exchange rate from GBP to Polish złoty and prints it to the screen.

{$mode objfpc}{$H+}

uses fphttpclient, fpjson, jsonparser;

Var
  S : String;
  J: TJSONData;
  initialAmount, endAmount, rate: real;

begin
  With TFPHttpClient.Create(Nil) do
    try
      S:=Get('http://api.fixer.io/latest?base=GBP');
    finally
      Free;
    end;
    J:= GetJSON(S);
    writeln ('Current exchange rate of GBP to Polish złoty: ',J.FindPath('rates.PLN').AsFloat:2:2);
end. 

What I'm struggling to do is pass the value of that exchange rate to a variable that I can use for currency conversion.

Something along the lines of this:

rate := J.FindPath('rates.PLN').AsFloat:2:2;
writeln;
write ('Enter initial amount in GBP £');
readln (initialAmount);
endAmount := initialAmount * rate;
writeln (endAmount);    

Any suggestions?


Solution

  • Your proposed code looks fine, apart from two problems.

    1. I would expect the compiler to report the first problem: remove the :2:2. IIRC, that notation is reserved for the WriteLn statement.

    2. The second problem should be obvious if you read the code: on the last line, you're printing the rate instead of the end amount.