| Thread overview | |||||||
|---|---|---|---|---|---|---|---|
|
December 03, 2015 Strange behaviour of to!string and JSON | ||||
|---|---|---|---|---|
| ||||
void login(HTTPServerRequest req, HTTPServerResponse res)
{
Json request = req.json;
writeln(to!string(request["username"]));
writeln(request["username"].to!string);
}
Why first code print output with quotes, and second not?
"asd"
asd
| ||||
December 03, 2015 Re: Strange behaviour of to!string and JSON | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Suliman | Am 03.12.2015 um 09:46 schrieb Suliman:
> void login(HTTPServerRequest req, HTTPServerResponse res)
> {
> Json request = req.json;
> writeln(to!string(request["username"]));
> writeln(request["username"].to!string);
> }
>
> Why first code print output with quotes, and second not?
> "asd"
> asd
The first one calls std.conv.to, which in turn calls Json.toString(), while the second calls Json.to!string(), which converts the value that is stored in the Json object to a string.
Probably the "to" method needs to be renamed to something else ("convertTo"?). But isn't there a way to customize std.conv.to!T for T other than string? I guess that was my hope when I named it like that four years ago.
| |||
December 03, 2015 Re: Strange behaviour of to!string and JSON | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Suliman | On Thursday, 3 December 2015 at 08:46:44 UTC, Suliman wrote: > void login(HTTPServerRequest req, HTTPServerResponse res) > { > Json request = req.json; > writeln(to!string(request["username"])); > writeln(request["username"].to!string); > } > > Why first code print output with quotes, and second not? > "asd" > asd I regularly use request["username"].get!string; in these cases, as I find it reads better and is more consistent with what you're actually doing. http://vibed.org/api/vibe.data.json/Json.get Also, I think this is the case (haven't used it in a while), get!string will fail if the item it's getting ISNT a string, while to!string wont. | |||
December 03, 2015 Re: Strange behaviour of to!string and JSON | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Sönke Ludwig | On Thursday, 3 December 2015 at 10:17:17 UTC, Sönke Ludwig wrote:
> But isn't there a way to customize std.conv.to!T for T other than string?
I believe you do that by implementing opCast?
| |||
December 07, 2015 Re: Strange behaviour of to!string and JSON | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Vladimir Panteleev | Am 03.12.2015 um 12:18 schrieb Vladimir Panteleev:
> On Thursday, 3 December 2015 at 10:17:17 UTC, Sönke Ludwig wrote:
>> But isn't there a way to customize std.conv.to!T for T other than string?
>
> I believe you do that by implementing opCast?
Right, forgot about that. Unfortunately that would stretch the semantics of cast() a bit too much in this case, IMO. It would certainly be good to have an alternative hook for high-level conversions.
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply