I want to generate a json row using a Class, I overwrite the gist method, so that it will print what I want:
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); 
but fails with:
===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
What I want is:
{"ev":"app","ak":"7111ac873c9dcd5fc335ded47630d050","uu":"15778787898988090","ifo":"true","st":"1523451601875"}
Why I can't use colon pair in qqww or qq:to struct?
{} have special meaning in double quote. They must be escaped 
qq:to「EOF」;
\{"ev":"app","ak":"$!ak","uu":"$!uu","ifo":"$!ifo","st":"$!st"\}
EOF
you need qq, not qqww which make list.
You can use fmt
(:ev<app>, :$!ak, :$!uu, :$!ifo, :$!st).fmt('"%s":"%s"', ',').fmt('{%s}')
or JSON::Fast
require JSON::Fast <&to-json>;
{:ev<app>, :$!ak, :$!uu, :$!ifo, :$!st}.&to-json
or even
require JSON::Fast <&to-json>;
self.^attributes.map( {.name => .get_value(self)} ).Hash.&to-json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With