On Wednesday, 29 July 2015 at 08:55:20 UTC, Sönke Ludwig wrote:
That would be another possibility. What do you think about the
opt(jv).foo.bar[12].baz alternative? One advantage is that it
could work without parsing a string and the implications
thereof (error handling?).
I implemented it too, but I removed.
Many times fields name are functions name or similar and it
breaks the code.
In my implementation it creates a lot of temporary objects (one
for each subobj) using the string instead, i just create the last
one.
It's not easy for me to use assignments with that syntax.
Something like:
obj.with.a.new.field = 3;
It's difficult to implement. It's much easier to implement:
obj["/field/doesnt/exists"] = 3
It's much easier to write formatted-string paths.
It allows future implementation of something like xpath/jquery
style
If your json contains keys with "/" inside, you can still use old
plain syntax...
String parsing it's quite easy (at compile time too) of course.
If a part of path doesn't exists it works like a part of opt("a",
"b", "c") doesn't. It's just syntax sugar. :)
Anyway, opt(...).isNull return true if that sub-obj doesn't
exists.
How can I check instead if that sub-object is actually null?
Something like: { "a" : { "b" : null} } ?
opt(...) == null
Does it works? Anyway it seems ambiguous:
opt(...) == null => false
opt(...).isNull => true
It would be nice to have a way to get a default if it doesn't
exists.
On my library that behave in a different way i write:
Object is : { address : { number: 15 } }
// as!xxx try to get a value of that type, if it can't it
tries to
convert it using .to!xxx if it fails again it returns default
// Converted as string
assert(obj["/address/number"].as!string == "15");
// This doesn't exists
assert(obj["/address/asdasd"].as!int == int.init);
// A default value is specified
assert(obj["/address/asdasd"].as!int(50) == 50);
// A default value is specified (but value exists)
assert(obj["/address/number"].as!int(50) == 15);
// This doesn't exists
assert(!obj["address"]["number"]["this"].exists);
My library has a get!xxx string too (that throws an exception
if value
is not xxx) and to!xxx that throws an exception if value can't
converted
to xxx.
I try to build this from existing building blocks in Phobos, so
opt basically returns a Nullable!Algebraic. I guess some of it
could simply be implemented in Algebraic, for example by adding
an overload of .get that takes a default value. Instead of .to,
you already have .coerce.
The other possible approach, which would be more convenient to
use, would be add a "default value" overload to "opt", for
example: jv.opt("defval").foo.bar
Isn't jv.opt("defval") taking the value of ("defval") rather than
setting a default value?