getOrFallback

Helper to get a value from a JSON object or return a fallback value if it doesn't exist.

Limitations: Only work on std.json.JSONType.object-type JSONValues.

static pure @safe
V
getOrFallback
(
V = string
)
(
const JSONValue json
,
const string key
,
const V fallback = V.init
)

Parameters

json JSONValue

JSONValue object to extract from.

key string

Key to look up in the JSON object.

fallback V

Value to return if the key is not found.

Return Value

Type: V

The value found in the JSON object, or the fallback value if the key was not found.

Examples

import std.conv : to;

{
    const json = JSONValue([ "abc" : "def", "ghi" : "jkl" ]);

    {
        const value = getOrFallback(json, "abc");
        assert((value == "def"), value);
    }
    {
        const value = getOrFallback(json, "ghi");
        assert((value == "jkl"), value);
    }
    {
        const value = getOrFallback(json, "mno");
        assert((value == string.init), value);
    }
    {
        const value = getOrFallback(json, "pqr", "INVALID");
        assert((value == "INVALID"), value);
    }
}
{
    const json = JSONValue([ "123" : 123, "456" : 456 ]);

    {
        const value = getOrFallback!long(json, "123");
        assert((value == 123L), value.to!string);
    }
    {
        const int value = getOrFallback!int(json, "456");
        assert((value == 456), value.to!string);
    }
    {
        const value = getOrFallback!long(json, "789");
        assert((value == 0L), value.to!string);
    }
    {
        const short value = getOrFallback!short(json, "012", 999);
        assert((value == 999), value.to!string);
    }
}