std.json - Any way to check if a JSONValue has a particular field

99 views Asked by At

Suppose I have an unknown bit of JSON, and I want to check if it has a form similar to this:

{
    "foo": stuff
    "bar": stuff
}

where stuff is anything - integer, object, whatever. If I do something like this:

auto json = parseJSON("{}");
auto foo = json["foo"];

I will get a segfault. Is there any way to gracefully handle this (return null, throw exception, anything other than a segfault)?

1

There are 1 answers

4
Vladimir Panteleev On BEST ANSWER

Just use the D in operator, like with a D associative array:

auto foo = "foo" in json ? json["foo"].str : null;

If you're using DMD 2.065 or older, you need to use json.object for the in operator:

auto foo = "foo" in json.object ? json["foo"].str : null;