我想使用Class
生成json行,我会覆盖gist
方法,以便打印出我想要的内容:
my $ak = '7111ac873c9dcd5fc335ded47630d050';
my $st = '1523451601875';
my $ifo = 'true';
my $uu = "15778787898988090";
class Stay {
has $.ak is rw = '7111ac873c9dcd5fc335ded47630d050';
has $.uu is rw;
has $.ifo is rw;
has $.st is rw;
method gist() {
#return qqww/{"ev":"app","ak":"$!ak","uu":"$!uu","ifo":"$!ifo","st":"$!st"}/;
return qqww:to「EOF」;
{"ev":"app","ak":"$!ak","uu":"$!uu","ifo":"$!ifo","st":"$!st"}
EOF
}
}
say Stay.new(uu => $uu, ifo => $ifo, st => $st);
但失败了:
===SORRY!=== Error while compiling /Users/ohmycloud/Desktop/stay.pl6
Confused
at /Users/ohmycloud/Desktop/stay.pl6:18
------> {"ev":⏏"app","ak":"$!ak","uu":"$!uu","ifo":"$!i
expecting any of:
colon pair
我想要的是:
{"ev":"app","ak":"7111ac873c9dcd5fc335ded47630d050","uu":"15778787898988090","ifo":"true","st":"1523451601875"}
为什么我不能在qqww
或qq:to
结构中使用冒号对?
答案 0 :(得分:6)
{}
在双引号中有特殊含义。他们必须逃脱
qq:to「EOF」;
\{"ev":"app","ak":"$!ak","uu":"$!uu","ifo":"$!ifo","st":"$!st"\}
EOF
您需要qq
,而不是列出的qqww
。
您可以使用fmt
(:ev<app>, :$!ak, :$!uu, :$!ifo, :$!st).fmt('"%s":"%s"', ',').fmt('{%s}')
或JSON::Fast
require JSON::Fast <&to-json>;
{:ev<app>, :$!ak, :$!uu, :$!ifo, :$!st}.&to-json
甚至
require JSON::Fast <&to-json>;
self.^attributes.map( {.name => .get_value(self)} ).Hash.&to-json
答案 1 :(得分:4)
您可以使用unquoting:
index
将返回
method gist() {
return '{"ev":"app","ak":"\qq[$!ak]","uu":"\qq[$!uu]","ifo":"\qq[$!ifo]","st":"\qq[$!st]"}':
}
如果你使用{"ev":"app","ak":"7111ac873c9dcd5fc335ded47630d050","uu":"15778787898988090","ifo":"true","st":"1523451601875"}
或类似的话,冒号会妨碍你。