Search code examples
jsondphobos

std.json - A bit confused with TRUE, FALSE and NULL values


I was looking over the std.json library as part of program I am working on, and I'm a bit confused about how to get data out of JSONValues whose types are inferred as TRUE, FALSE or NULL.

For example, if I parse the following JSON:

{
    "foo" : "bar"
}

I can then extract the string held in the attribute "foo" by doing something like:

auto json = parseJSON("/path/to/json/example.json");
auto foo_attr = json["foo"].str;

But suppose instead that I had JSON like this:

{
    "foo" : false,
    "bar" : true,
    "baz" : null
}

What would I need to do to get at the attribute values of "foo", "bar" and "baz"?


Solution

  • Look at the variable's type.

    auto json = parseJSON("/path/to/json/example.json");
    bool foo = json["foo"].type == JSON_TYPE.TRUE;
    bool bar = json["bar"].type == JSON_TYPE.TRUE;
    bool bazIsNull = json["baz"].type == JSON_TYPE.NULL;
    

    Of course, if you expect that values might have other types, you'll need extra checks.