std.json API improvement - Request for code review

Robert Jacques sandford at jhu.edu
Tue Sep 14 21:44:05 PDT 2010


On Tue, 14 Sep 2010 17:48:25 -0400, sybrandy <sybrandy at gmail.com> wrote:

>> Unfortunately, the above code is horribly broken. Here's how to read a
>> number correctly:
>>
>> 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);
>> }
>>
>> You'll notice that before any access you must check to ensure the JSON
>> type is what you think it should be. As noted above, JSON does not
>> differentiate between integers and reals, so you have to test both on
>> access.
>
> Understood.  Even though this probably isn't the way it will end up  
> based on some previous discussion, I like the way the indices are used  
> to access the elements.  Perhaps this means I'm more of a C guy than a D  
> guy in some respects.  Definitely not a Java guy.

And the really awesome thing about D is that its trivial to support both  
json.vector.x and json["vector"]["x"] syntaxes.

> As for the integers vs. floats, does the API always treat a number as a  
> float even if it is an integer?  If so, then checking for an integer vs.  
> a float may not be a big deal in many cases.
>
> Casey

Nope. The current std.json dynamically checks if a number is an integer or  
real and stores the data accordingly. So you'd have to do the checks.


More information about the Digitalmars-d mailing list