www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Strange behaviour of to!string and JSON

reply Suliman <evermind live.ru> writes:
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
Dec 03 2015
next sibling parent reply =?UTF-8?Q?S=c3=b6nke_Ludwig?= <sludwig rejectedsoftware.com> writes:
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.
Dec 03 2015
parent reply Vladimir Panteleev <thecybershadow.lists gmail.com> writes:
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?
Dec 03 2015
parent =?UTF-8?Q?S=c3=b6nke_Ludwig?= <sludwig outerproduct.org> writes:
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.
Dec 07 2015
prev sibling parent wobbles <grogan.colin gmail.com> writes:
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.
Dec 03 2015