Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a particular element exists in SuperObject?

I widely use the SuperObject JSON library. I need to be able to check if a particular element exists in an object or not. I can check the value of an element, for example an integer that doesn't exist returns 0. However, 0 is one of the possible values if it does exist - so I can't depend on observing 0 for the element's existence. I checked the ISuperObject for methods that can do this (for example I'd expect something like ISuperObject.Exists(const S: String): Boolean;), but see nothing like this.

How can I check if a particular element exists in the JSON object or not?

like image 789
Jerry Dodge Avatar asked May 25 '14 18:05

Jerry Dodge


2 Answers

The latest update of SuperObject contains an Exists() function.

var
  obj : ISuperObject;
begin
  obj := TSuperObject.ParseFile('..\..\SAMPLE.JSON',FALSE);
  if not obj.AsObject.Exists('FindMe') then begin
    WriteLn('Not found');
  end;
end;

If you should use the dwsJSON parser instead, there is a similar function to use:

if json['DoesNotExists'].ElementCount = 0 then begin
  WriteLn('Not found');
end;
like image 142
LU RD Avatar answered Nov 09 '22 16:11

LU RD


You can check if certain field exists like this:

function FieldExists(const ASuperObject: ISuperObject; const AField: String): Boolean;
var
  o: ISuperObject;
begin
  o := ASuperObject.O[AField];
  result := Assigned(o);
end;

Basically, json_superobject.O[field_name] should return pointer to ISuperObject if field_name exists. Otherwise, it returns nil.

like image 22
rsrx Avatar answered Nov 09 '22 16:11

rsrx