Home > Net >  X-SuperObject thinks that non existent keys exists
X-SuperObject thinks that non existent keys exists

Time:02-05

There's code a minimum reproducible example in my previous question. Please let me know if you want it copied here.

Basically, I noticed that this code:

if Assigned(job['Employer.Name.Normalized']) then
   Memo1.Lines.Add('Employer name = '   job['Employer.Name.Normalized'].AsString);

was adding an empty string to the memo.

Hardly surprising, as the JSON looks like this:

                    "Id": "POS-10",
                    "Employer": {
                        "Location": {
                            "CountryCode": "UK",
                            "Municipality": "Bradford"
                        }
                    },
                    "IsSelfEmployed": false,
                    "IsCurrent": false,
                    ... etc

So, why does Assigned(job['Employer.Name.Normalized']) evaluate to true?

Note that Assigned(job.O['Employer'].O['Name'].O['Normalized']) gives the same result, but, AFIAK, it's just syntactic sugar as how it is written.

So, I tried random keys: Assigned(job['StackOverlow]) evaluates to true, as does Assigned(job['Why is this not false???'])

What am I doing wrongly? And how to I detect if a key actually exists in the ISuperObject which was obtained from my JSON?

CodePudding user response:

This is working as designed.

When you reference a member object or array, and that member doesn't exist, XSuperObject creates a new member. This lets users easily create new JSON documents.

To search for a member without creating it, use the Contains() method instead, eg:

if job.Contains('Employer') then
begin
  emp := job.O['Employer'];
  if emp.Contains('Name') then
  begin
    nam := emp.O['Name'];
    if nam.Contains('Normalized') then
      Memo1.Lines.Add('Employer name = '   nam.S['Normalized']);
  end;
end;
  • Related