How to check if a specific item exists in SuperObject?

I use the SuperObjectJSON library extensively . I need to check if any particular element exists in the object or not. I can check the value of an element, for example an integer that does not exist returns 0. However, it 0is one of the possible values ​​if it exists, so I cannot depend on observation 0for the existence of the element. I checked ISuperObjectfor methods that can do this (for example, I would expect something like ISuperObject.Exists(const S: String): Boolean;), but I don't see anything like it.

How to check if any specific element exists in a JSON object?

+4
source share
2 answers

The latest SuperObject update contains a feature Exists().

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 must use the dwsJSON parser , a similar function will be used:

if json['DoesNotExists'].ElementCount = 0 then begin
  WriteLn('Not found');
end;
+5
source

You can check if a specific field exists, for example:

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 a pointer to ISuperObjectif field_nameexists. Otherwise, it returns nil.

+4
source

Source: https://habr.com/ru/post/1541963/


All Articles