Skip to content

Commit

Permalink
add JSONValue.isNull
Browse files Browse the repository at this point in the history
- short-access similar to array, str, object...
- val.type == JSON_TYPE.NULL is fairly verbose
  • Loading branch information
MartinNowak committed Nov 22, 2014
1 parent 7e80e67 commit 8b7322a
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions std/json.d
Expand Up @@ -197,6 +197,12 @@ struct JSONValue
return store.array;
}

/// Test whether the type is $(D JSON_TYPE.NULL)
@property bool isNull() const
{
return type == JSON_TYPE.NULL;
}

private void assign(T)(T arg)
{
static if(is(T : typeof(null)))
Expand Down Expand Up @@ -342,7 +348,7 @@ struct JSONValue
return *enforce!JSONException(k in store.object,
"Key not found: " ~ k);
}

/// Operator sets $(D value) for element of JSON object by $(D key)
/// If JSON value is null, then operator initializes it with object and then
/// sets $(D value) for it.
Expand All @@ -352,10 +358,10 @@ struct JSONValue
{
enforceEx!JSONException(type == JSON_TYPE.OBJECT || type == JSON_TYPE.NULL,
"JSONValue must be object or null");

if(type == JSON_TYPE.NULL)
this = (JSONValue[string]).init;

store.object[key] = value;
}

Expand Down Expand Up @@ -999,6 +1005,12 @@ unittest
assert(index == (value.integer-3));
}

jv = null;
assert(jv.type == JSON_TYPE.NULL);
assert(jv.isNull);
jv = "foo";
assert(!jv.isNull);

jv = JSONValue("value");
assert(jv.type == JSON_TYPE.STRING);
assert(jv.str == "value");
Expand Down Expand Up @@ -1203,28 +1215,28 @@ deprecated unittest
unittest
{
// Bugzilla 12969

JSONValue jv;
jv["int"] = 123;

assert(jv.type == JSON_TYPE.OBJECT);
assert("int" in jv);
assert(jv["int"].integer == 123);

jv["array"] = [1, 2, 3, 4, 5];

assert(jv["array"].type == JSON_TYPE.ARRAY);
assert(jv["array"][2].integer == 3);

jv["str"] = "D language";
assert(jv["str"].type == JSON_TYPE.STRING);
assert(jv["str"].str == "D language");

jv["bool"] = false;
assert(jv["bool"].type == JSON_TYPE.FALSE);

assert(jv.object.length == 4);

jv = [5, 4, 3, 2, 1];
assert( jv.type == JSON_TYPE.ARRAY );
assert( jv[3].integer == 2 );
Expand Down

0 comments on commit 8b7322a

Please sign in to comment.