3

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 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.