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

1.1k Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.