Followin开发者_如何学JAVAg code always print paths with double slashes:
use JSON;
use File::Spec;
my $installdir = $ENV{"ProgramFiles"};
my $xptrlc = File::Spec->catfile($installdir,"bin","sample");
my $jobhash;
my $return_packet;
$jobhash->{'PATH'} = $xptrlc;
$return_packet->{'JOB'} = $jobhash;
my $js = new JSON;
my $str = $js->objToJson($return_packet);
print STDERR "===> $str \n";
OUTPUT of this script is
===> {"JOB":{"PATH":"C:\\Program Files (x86)\\bin\\sample"}}
Any solution to remove those double \\
slashes?
As Greg mentioned, the '\
' character is represented as '\\
' in JSON.
http://www.ietf.org/rfc/rfc4627.txt?number=4627
If you intend to use "thaw" the JSON somewhere, like in another Perl program or in JavaScript, you will still get back exactly what you put in.
Are you trying to do something else with your JSON?
Windows is perfectly fine with using '/'
in paths if that bothers you so much:
use strict; use warnings;
use JSON;
use File::Spec::Functions qw(catfile);
my $installdir = $ENV{ProgramFiles};
my $xptrlc = catfile $installdir,qw(bin sample);
$xptrlc =~ s'\\'/'g;
my $packet = { JOB => { PATH => $xptrlc } };
my $js = JSON->new;
my $str = $js->encode($packet);
warn "===> $str \n";
Output:
===> {"JOB":{"PATH":"C:/Program Files/bin/sample"}}
On the other hand, the encoded value will be correctly decoded:
use JSON;
warn JSON->new->decode(scalar <DATA>)->{JOB}->{PATH}, "\n";
__DATA__
{"JOB":{"PATH":"C:\\Program Files (x86)\\bin\\sample"}}
Output:
C:\Temp> ht C:\Program Files (x86)\bin\sample
精彩评论