in reply to Outputting JSON with function () {...} values
As the others have said, that's not JSON, and it's unclear what Perl structure you would want to translate to a JS function. Could you show an example of such a Perl data structure, and the equivalent JavaScript that you expect to get?
Anyway, for WebPerl, I also looked into exactly this question and found that at least Cpanel::JSON::XS, and it seems the other JSON modules too, do not provide a good way to hook into the serialization to accomplish this. I ended up writing my own simple serializer. Something like this:
use warnings; use strict; use Cpanel::JSON::XS; our $JSON = Cpanel::JSON::XS->new->allow_nonref; sub to_js { my $what = shift; if (my $r = ref $what) { if ($r eq 'HASH') { return '{' . join(',', map { $JSON->encode("$_").':'.to_js($$what{$_}) } sort keys %$what ) . '}'; } elsif ($r eq 'ARRAY') { return '[' . join(',', map { to_js($_) } @$what) . ']'; } elsif ($r eq 'CODE') { return 'function () { /* some JS here? */ }'; } else { die "can't encode ref $r to JS" } } else { return $JSON->encode($what) } } print to_js( { foo => [ "bar", "quz" ], baz => sub {}, } ), "\n"; __END__ {"baz":function () { /* some JS here? */ },"foo":["bar","quz"]}
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Outputting JSON with function () {...} values
by Aldebaran (Curate) on Oct 25, 2018 at 06:23 UTC | |
by haukex (Archbishop) on Oct 25, 2018 at 07:51 UTC | |
by LanX (Saint) on Oct 25, 2018 at 06:56 UTC |