Jump to content
JIMSMITH

Looking for containskey when processing data

Recommended Posts

I am using Delphi 10.1 update2.  When processing a json file I cannot find the containskey method with a TJSONObject?  Is there a work around to the the equivalent check JSONObject.containskey('keyvalue') for this version of Delphi?

 

Share this post


Link to post
15 hours ago, JIMSMITH said:

I am using Delphi 10.1 update2.  When processing a json file I cannot find the containskey method with a TJSONObject?

TJSONObject does not have a ContainsKey() method, in any version of Delphi.  If you want that, you can use a class helper, eg:

type
  TJSONObjectHelper = class helper for TJSONObject
    function ContainsKey(const AKeyName: String): Boolean;
  end;

function TJSONObjectHelper.ContainsKey(const AKeyName: String): Boolean;
begin
  Result := Self.GetValue(AKeyName) <> nil;
end;

...

if JSONObject.ContainsKey('keyvalue') then
15 hours ago, JIMSMITH said:

Is there a work around to the the equivalent check JSONObject.containskey('keyvalue') for this version of Delphi?

As you can see above, you can use the TJSONObject.GetValue() method, which returns nil if the specified key is not found, eg:

if (JSONObject.GetValue('keyvalue') <> nil) then

 

Edited by Remy Lebeau

Share this post


Link to post
5 hours ago, pyscripter said:

There is also TryGetValue<T>.

True, though it is inherited from TJSONValue and not specific to TJSONObject, it has a little more overhead as it performs path processing on the input string and type validation on the output value, and it requires the caller to declare a variable to receive the output value whether the caller actually wants it or not.

Edited by Remy Lebeau
  • Thanks 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×