While trying to create a JSON message for an API, I found myself struggling to do something that I thought would be simple. I needed to create a message like the following:
{ "list": [ { "foo": 1, "bar": 2 } ] }
However, my first attempt did not work:
say to-json { foo => [ { a => 1, b => 2 } ] };
# {"foo":[{"a":1},{"b":2}]}
Trying to simplify things further confused me more:
say { foo => [ { a => 1 } ] };
# {foo => [a => 1]}
# Note that this is not JSON, but I expected to see curly braces
Then I tried to use some temporary variables, and that worked:
my @list = { a => 1 };
say to-json { foo => @list };
# {"foo":[{"a":1}]}
my %hash = ( a => 1 );
say to-json { foo => [ %hash ] };
# {"foo":[{"a":1}]}
What's going on here?
And is there a way I can achieve my desired output without an extra temporary variable?
say to-json { foo => [ { a => 1 } ] };
should output something like{"foo":[{"a":1}]}
, not{"foo":["a":1]}
. The latter is a typo, right? If not, what doessay $*PERL.compiler.version;
say?say to-json { foo => [ a => 1 ] }
outputs{"foo":[{"a":1}]}
so who knows what I typed when I got that, if I ever did. My bad!