views:

215

answers:

3

Following 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?

+7  A: 

As Greg mentioned, the '\' character is represented as '\\' in JSON.

http://www.ietf.org/rfc/rfc4627.txt?number=4627

Sean
+3  A: 

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
Sinan Ünür
Amen. I wish more people knew this trick. I've seen so much "portable" code jump through needless hoops trying to handle windows paths.
Andy Ross
Hoops are still required. `/C:/Program Files/bin/sample` is not valid, after all.
jrockway
Not sure I follow. That's a perfectly valid windows path AFAICT. It lives underneath a directory named "C:" on the current drive. Obviously the filesystem layouts are different, but an app with a given file structure under the cwd can always use the same paths between systems.
Andy Ross
+4  A: 

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?

Tim