in reply to Perl structure to Javacript-ready JSON
The following isn't JSON:
{"abc":"abc\'abc"}
What are you trying to do? You might be trying to generate a JavaScript string literal from JSON, but then you'd want something like the following.
'{"abc":"abc\'abc"}'
If that's what you want, you can use the following:
{ my %translations = ( "\r" => "\\r", "\n" => "\\n", "'" => "\\'", "\\" => "\\\\", ); my $meta_chars_class = join '', map quotemeta, keys %translations; my $meta_chars_re = qr/([$meta_chars_class])/; sub text_to_jslit { my $text = shift; $text =~ s/$meta_chars_re/$translations{$1}/g; return "'$text'"; } }
As a Template-Toolkit plugin:
package Template::Plugin::JavaScriptLiteral; use strict; use warnings; use Template::Plugin::Filter qw( ); our @ISA = 'Template::Plugin::Filter'; my %translations = ( "\r" => "\\r", "\n" => "\\n", "'" => "\\'", "\\" => "\\\\", ); my $meta_chars_class = join '', map quotemeta, keys %translations; my $meta_chars_re = qr/([$meta_chars_class])/; sub init { my $self = shift; $self->install_filter('jslit'); return $self; } sub filter { my ($self, $text) = @_; $text =~ s/$meta_chars_re/$translations{$1}/g; return "'$text'"; } 1;
For example,
// PARAMS: { data => { abc => "abc'abc" } } [% USE JSON %] [% USE JavaScriptLiteral %] var json = [% data | json | jslit %]; alert(json); // {"abc":"abc'abc"}
However, one usually wants to assign the JSON to a JS var, not a string representation of it.
// PARAMS: { data => { abc => "abc'abc" } } [% USE JSON %] var data = [% data | json %]; alert(data.abc); // abc'abc
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl structure to Javacript-ready JSON
by Jeppe (Monk) on Nov 26, 2014 at 08:21 UTC | |
by ikegami (Patriarch) on Nov 26, 2014 at 14:18 UTC | |
by LanX (Saint) on Nov 26, 2014 at 16:16 UTC |