std.json parsing issues

Jonathan Marler johnnymarler at gmail.com
Wed Nov 6 23:14:45 UTC 2019


On Wednesday, 6 November 2019 at 21:48:48 UTC, GrimMaple wrote:
> Hello everyone! I'm fairly new to D and don't know much about 
> its internals, but I've been playing around with std.json and 
> found out a pretty weird behaviour in it. Let's say I have a 
> JSON like this: { "Value": 123 }. When I parse it and try to 
> writeln(json["Value"].floating) it throws a runtime error 
> saying that "Value" is not "floating". I understand that it's 
> being taken as an integer, but aren't integers subset of 
> decimals? I would expect it to be able to convert to float no 
> problem, but it's not the case. Does anyone know if this 
> behaviour is intended or if it's a bug?

Looking at the json spec, it looks like it doesn't distinguish 
between integers and floating point values.

As D is a native language, the distinction between integer and 
floating point values it semantically important.  The operations 
on each have very different behavior.

That being said, adding support in `std.json` to interpret both 
integers and floating points as floats should be trivial to 
implement.  Or you could add your own function in your app.

float asFloating(JSONValue value)
{
     return (value.type == JSONType.integer) ?
         cast(float)value.integer : value.floating;
}

auto json = parseJSON(`{"num":123}`);
writefln("num is: %s", json["num"].asFloating);
json = parseJSON(`{"num":123.456}`);
writefln("num is: %s", json["num"].asFloating);



More information about the Digitalmars-d mailing list