On Monday, 4 August 2014 at 16:58:12 UTC, Andrei Alexandrescu
wrote:
On 8/4/14, 12:47 AM, Andrea Fontana wrote:
On my bson library I found very useful to have some methods to
know if a
field exists or not, and to get a "defaulted" value. Something
like:
auto assume(T)(Value v, T default = T.init);
Nice. Probably "get" would be better to be in keep with
built-in hashtables.
I wrote assume just to use proposed syntax :)
Another good method could be something like xpath to get a
deep value:
Value v = value["/path/to/sub/object"];
Cool. Is it unlikely that a value contains an actual slash? If
so would be value["path"]["to"]["sub"]["object"] more precise?
Key with a slash (or dot?) inside is not common at all. Never
seen on json data.
In many languages there're libraries to bind json to struct or
objects so usually people doesn't use strange chars inside key.
If needed you can still use old good method to read a single
field.
value["path"]["to"]["object"] was my first choice but i didn't
like it.
First: it create a lot of temporary objects.
Second: it is easier to implement using a single string (also on
assignment)
I gave it a try with value["path", "to", "index"] but it's not
confortable if you need to generate your path from code.
Moreover in my library I actually have three different methods
to read a
value:
T get(T)() // Exception if value is not a T or not valid or
value
doesn't exist
T to(T)() // Try to convert value to T using to!string.
Exception if
doesn't exists or not valid
BsonField!T as(T)(lazy T default = T.init) // Always return a
value
BsonField!T is an "alias this"-ed struct with two fields: T
value and
bool error(). T value is the aliased field, and error() tells
you if
value is defaulted (because of an error: field not exists or
can't
convert to T)
So I can write something like this:
int myvalue = json["/that/deep/property"].as!int;
or
auto myvalue = json["/that/deep/property"].as!int(10);
if (myvalue.error) writeln("Property doesn't exists, I'm using
default
value);
writeln("Property value: ", myvalue);
I hope this can be useful...
Sure is, thanks. Listen, would you want to volunteer a
std.data.json proposal?
What does it mean? :)
Andrei