Recent

Author Topic: json, how to handle an empty value?  (Read 473 times)

Nicole

  • Hero Member
  • *****
  • Posts: 1324
json, how to handle an empty value?
« on: August 04, 2025, 08:56:03 pm »
here is a method, which fomats json:

Code: Pascal  [Select][+][-]
  1. function TKurse_prep.FormatiereSuche (JsonArray: TJSONArray): string;
  2. var i: Integer;
  3.     Symbol, Name, Currency, StockExchange, ExchangeShortName: string;
  4.     JsonObject: TJSONObject;
  5. begin
  6.   Result := '';
  7.  
  8.   for i := 0 to JsonArray.Count - 1 do
  9.   begin
  10.     JsonObject := JsonArray.Items[i] as TJSONObject;
  11.  
  12.     // Zugriff auf spezifische Felder mit 'Find' - Fehlerbehandlung für fehlende Felder
  13.     Symbol := JsonObject.Find('symbol').AsString;
  14.     Name := JsonObject.Find('name').AsString;
  15.     Currency := JsonObject.Find('currency').AsString;
  16.     StockExchange := JsonObject.Find('stockExchange').AsString;
  17.  
  18.     ExchangeShortName := JsonObject.Find('exchangeShortName').AsString;
  19.  
  20.     // das macht Probleme, uU ist es leer
  21.  
  22.     // Ergebnis auch dann hinzufügen, wenn eines der Felder fehlt
  23.     Result := Result + IntToStr(i) + ': Symbol: "' + Symbol + '", Name: "' +
  24.              Name + '", Währung: "' + Currency + '", Börse: "' +
  25.              StockExchange + '", Börsenkürzel: "' + ExchangeShortName + '"' + #13#10;
  26.   end;
  27.  
  28.   Result:=trim(result);
  29.   if Result = '' then Result := 'Keine Ergebnisse gefunden.';
  30. end;

Works find, although somtimes this line gives me a error-message "must not be zero".

Code: Pascal  [Select][+][-]
  1. StockExchange := JsonObject.Find('stockExchange').AsString;

How to avoid an error message and just leave out this very string?

Gustavo 'Gus' Carreno

  • Hero Member
  • *****
  • Posts: 1353
  • Professional amateur ;-P
Re: json, how to handle an empty value?
« Reply #1 on: August 04, 2025, 09:30:00 pm »
Hey Nicole,

If you use a TJSONData first, then you have access to FindPath, which will return a nil if the node/path, is not present, which is what I think you're getting.

This has been my way of avoiding issues when some fields are missing:
Code: Pascal  [Select][+][-]
  1. var
  2.   JSONData: TJSONData;
  3.   JSONObject: TJSONObject;
  4. begin
  5. { ... }
  6.   JSONData:= JSONArray.Items[i] as TJSONData;
  7.   JSONObject:= JSONData.FindPath('stockExchange');
  8.   if Assigned(JSONObject) then
  9.     StockExchange:= JSONObject.AsString;
  10. { ... }
  11. end;

I think this should solve your problem.
But please double check my code. I did not run this on the IDE, I just typed from memory.

Cheers,
Gus
« Last Edit: August 04, 2025, 09:43:31 pm by Gustavo 'Gus' Carreno »

 

TinyPortal © 2005-2018