std.data.json formal review

Sönke Ludwig via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 29 01:55:18 PDT 2015


Am 29.07.2015 um 09:46 schrieb Andrea Fontana:
> On Tuesday, 28 July 2015 at 14:07:19 UTC, Atila Neves wrote:
>> Start of the two week process, folks.
>>
>> Code: https://github.com/s-ludwig/std_data_json
>> Docs: http://s-ludwig.github.io/std_data_json/
>>
>> Atila
>
> Why don't do a shortcut like:
>
> jv.opt("/this/is/a/path") ?
>
> I use it in my json/bson binding.

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?).

> 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

>
> 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

>
> Other feature:
> // This field doesn't exists return default value
> auto tmpField = obj["/address/asdasd"].as!int(50);
> assert(tmpField.error == true);   // Value is defaulted ...
> assert(tmpField.exists == false); // ... because it doesn't exists
> assert(tmpField == 50);
>
> // This field exists, but can't be converted to int. Return default value.
> tmpField = obj["/tags/0"].as!int(50);
> assert(tmpField.error == true);   // Value is defaulted ...
> assert(tmpField.exists == true);  // ... but a field is actually here
> assert(tmpField == 50);



More information about the Digitalmars-d mailing list