Get and show json data from website's APIs in Delphi XE
delphi, delphi-xe, httprequest, json, python
Solution
You can use the `DBXJSON` unit to parse the JSON response.
Try this sample
var
LJsonObj : TJSONObject;
LJsonValue : TJSONValue;
begin
mydata := GetURLAsString('https://www.bitstamp.net/api/ticker/');
LJsonObj := TJSONObject.ParseJSONValue(TEncoding.Default.GetBytes(mydata),0) as TJSONObject;
try
LJsonValue := LJsonObj.Get('last').JsonValue;
Label1.Text:= LJsonValue.Value;
finally
LJsonObj.Free;
end;
end;
Problem
I am trying to re-write a piece of code I wrote in Python to Delphi. The Python code is: ``` url = "https://www.bitstamp.net/api/ticker/" response = urllib.urlopen(url) data = json.loads(response.read()) lastvalue = data['last'] ``` And this is enough to assign to the variable called "lastvalue" the value that I get from bitstamp's API. I would like to do the same thing with delphi (I am using delphi XE6). I tried to find some answer here, and I am able to connect to the bitstamp's website and to get the full string, by doing this: ``` function GetURLAsString(const aurl: string): string; var lHTTP: TIdHTTP; begin lHTTP := TIdHTTP.Create(nil); try lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP); Result := lHTTP.Get(aURL); finally lHTTP.Free; end; end; ``` And then I call this function with this: ``` procedure TForm2.Button1Click(Sender: TObject); var mydata : string; begin mydata := GetURLAsString('https://www.bitstamp.net/api/ticker/'); Label1.Text := mydata; end; ``` I'm stuck here. I searched a lot but I am not able to figure out how can I assign to Label1.Text just the value assigned to "last". When I run this I get `{"high": "629.40", "last": "622.00", "timestamp": "1401544416", "bid": "621.99", "vwap": "617.47", "volume": "15147.30475739", "low": "602.26", "ask": "622.00"}` assigned to Label1.Text. I hope I was able to explain the question. I am really stuck in this point for some days, I hope someone can help me.