stdx.data.json needs a layer on top

Sönke Ludwig via Digitalmars-d digitalmars-d at puremagic.com
Wed Jun 24 22:52:28 PDT 2015


Am 24.06.2015 um 15:48 schrieb Laeeth Isharc:
> So it would be nice to be able to something like Adam Ruppe does here:
> https://github.com/adamdruppe/arsd/blob/master/jsvar.d
>
> var j = json!q{
>          "hello": {
>              "data":[1,2,"giggle",4]
>          },
>          "world":20
>      };
>
>      writeln(j.hello.data[2]);
>
> Obviously the scope is outside a serialization library, but just
> thinking about the broader integrated and coherent library offering we
> should have.

This is very close to what I had done initially for vibe.d's "Json" 
struct. However, this approach requires adding opDispatch with an 
unbounded input domain. This in turn means that *any* change of the 
normal members in the Json struct is a potential silent breaking change. 
In particular, it then de-facto becomes impossible to add new methods.

Another issue that has come up is that such a struct passes all kinds of 
duck typing tests, so that for example it was considered to be an input 
range when it really isn't. This can be an issue for things like a 
serialization library that don't include a special case for this type.

Finally, although this is partially a matter of taste, I personally 
found that using the member access syntax can lead to the wrong (sub 
conscious) impression that these members were statically declared. I 
suspect that this leads to a larger likelihood that bugs caused by 
missing field existence checks slip into the source, as well as making 
it more difficult for the developer to detect typos (member access 
*looks* like it would be normal statically checked code, so it's easy to 
overlook typos there).

For these reasons, the code with the proposed JSONValue becomes a little 
more verbose, requiring index based access instead:

     auto j = parseJSONValue(q{
         "hello": {
             "data":[1,2,"giggle",4]
         },
         "world":20
     });

     writeln(j["hello"]["data"][2]);

There is also a method to safely (without causing exceptions) iterate 
down a path within the JSON DOM, when parts of the path might be missing:

     writeln(j.opt("hello", "data")[2]);

JSONValue is backed by a std.variant.Algebraic, which has the advantage 
of getting the operators for free. It also means that JSONValue will 
automatically be compatible with other similar value types, such as a 
potential BSONValue (which has more types to choose from).

[1]: 
http://s-ludwig.github.io/std_data_json/stdx/data/json/value/JSONValue.html


More information about the Digitalmars-d mailing list