Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON with SuperObject: is element an array or an object?

I get JSON from API and it have a quirk: usually it returns "tags" element as object {"x":"y"}, but if ther are no tags, it returns empty array [] instead.

I parse JSON with SuperObject, and use this code:

var
  JsonObject: ISuperObject;
  item: TSuperAvlEntry;
  temp: TStringList;
begin
{...}
      for item in JsonObject.O['tags'].AsObject do
      begin
        temp.Add(item.Name);
      end;
{...}

It works wonderfully for objects, but it crashes with Access Violation error if it's an array.

As well, if I try something like:

if JSONObject['tags'].AsArray.Length=0 then

it works fine for empty array, but crashes if it is an object.

I don't know for sure that elements may be in "tags" and thus don't know how can I use Exists() in this case.

Any ideas?

like image 510
Alexander Avatar asked Mar 25 '26 13:03

Alexander


1 Answers

Well, looks like I found the answer myself, so I will share it.

ISuperObject has a property "DataType" which you can check, like this:

if JsonObject['tags'].DataType = stObject then
begin
  for item in JsonObject.O['tags'].AsObject do
  begin
    temp.Add(item.Name);
  end;
end;

stObject and stArray are most useful to check, but there's also: stBoolean, stDouble, stCurrency, stInt and stMethod.

like image 62
Alexander Avatar answered Mar 27 '26 08:03

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!