std.json API improvement - Request for code review
Robert Jacques
sandford at jhu.edu
Sun Sep 12 20:45:17 PDT 2010
On Sun, 12 Sep 2010 05:05:09 -0400, Brian Schott <brian-schott at cox.net>
wrote:
> Now that a few bugs are fixed in DMD (notably 4826), my improvements to
> std.json compile. My primary purpose in this code change is streamlining
> the process of creating JSON documents. You can now do stuff like this:
>
> auto json = JSONValue();
> json["numbers"] = [1, 3, 5, 7];
> json["nullValue"] = null;
> json["something"] = false;
> json["vector"] = ["x": 234.231, "y" : 12.8, "z" : 35.0];
> assert("vector" in json);
> json["vector"]["x"] = 42.8;
>
> More example usage:
> http://www.hackerpilot.org/src/phobos/jsontest.d
>
> The implementation of the actual JSON data structure and parsing /
> writing is unchanged. Ddoc comments were added so that the documentation
> page for the module won't be quite so empty.
>
> Implementation:
> http://www.hackerpilot.org/src/phobos/json.d
>
> I'd like to get this committed back to Phobos if there's a consensus
> that these changes make sense. Comments welcome. (Note: You'll need a
> DMD version built from SVN to use this)
>
> - Brian
Hi Brain,
This really belongs on the phobos mailing list as JSON isn't ready for
public consumption yet (as far as I know). I would suspect that it even
has a decent chance of being dropped in favor of serialization + variant.
The implementation has several bugs. First, it doesn't parse Unicode
escape sequences correctly (e.g. \u0026). Second, JSON has no integer
type. Third, the serializer with certain JSON value inputs will write a
JSON file that can not be read by the parser. It's also missing some key
features, like output range and human readable output support. The design
is very C-ish as opposed to D-ish: its composed of a bunch of free
functions / types all containing JSON in their name. (i.e. parseJSON).
These should all be encapsulated as member functions.
Getting more to the API itself, the reading of a JSON value is a use case
that just isn't considered currently. Consider:
// It's relatively simple to write to a JSON value
json["vector"]["x"] = 42.8;
// But reading it...
real x;
if(json["vector"]["x"].type == JSON_TYPE.INTEGER) {
x = json["vector"]["x"].integer;
} else if(json["vector"]["x"].type == JSON_TYPE.FLOAT) {
x = json["vector"]["x"].floating;
} else {
enforceEx!(JSONException)(false);
}
By contrast, this is the API on my personal JSON library:
json.vector.x = 42.8;
auto x = json.vector.x.number;
More information about the Digitalmars-d
mailing list