Skip to content

Commit

Permalink
fixed JSON Pointer escaping to be compliant with the latest version o…
Browse files Browse the repository at this point in the history
…f the spec
  • Loading branch information
kraih committed Jul 2, 2012
1 parent e6ac074 commit f44a48d
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 31 deletions.
1 change: 1 addition & 0 deletions Changes
@@ -1,6 +1,7 @@

3.02 2012-07-02
- Improved documentation.
- Fixed JSON Pointer escaping.

3.01 2012-07-01
- Improved CSS of built-in templates.
Expand Down
22 changes: 5 additions & 17 deletions lib/Mojo/JSON/Pointer.pm
Expand Up @@ -12,24 +12,12 @@ sub get { shift->_pointer(0, @_) }
sub _pointer {
my ($self, $contains, $data, $pointer) = @_;

# Tokenize pointer
# Parse pointer and walk data structure
$pointer = decode('UTF-8', url_unescape $pointer);
my ($escaped, @parts);
while (length(my $char = substr $pointer, 0, 1, '')) {

# Caret escaped
++$escaped and next if $char eq '^' && !$escaped;

# Slash
if ($char eq '/' && !$escaped) { push @parts, '' }

# Character
else { $parts[-1] .= $char }
$escaped = undef;
}

# Walk data structure
for my $p (@parts) {
return $data unless $pointer =~ s!^/!!;
for my $p (split '/', $pointer) {
$p =~ s/~0/~/g;
$p =~ s!~1!/!g;

# Hash
if (ref $data eq 'HASH' && exists $data->{$p}) { $data = $data->{$p} }
Expand Down
21 changes: 7 additions & 14 deletions t/mojo/json_pointer.t
Expand Up @@ -2,7 +2,7 @@ use Mojo::Base -strict;

use utf8;

use Test::More tests => 27;
use Test::More tests => 24;

# "I've had it with this school, Skinner.
# Low test scores, class after class of ugly, ugly children..."
Expand Down Expand Up @@ -49,17 +49,10 @@ is $p->get([{'foob ar' => 'foo'}], '/0/foob%20ar'), 'foo',
'"/0/foob%20ar" is "foo"';
is $p->get([{'foo/bar' => 'bar'}], '/0/foo%2Fbar'), undef,
'"/0/foo%2Fbar" is "undef"';
is $p->get([{'foo/bar' => 'bar'}], '/0/foo^%2Fbar'), 'bar',
'"/0/foo^%2Fbar" is "bar"';
is $p->get([{'foo/bar' => 'bar'}], '/0/foo%5E%2Fbar'), 'bar',
'"/0/foo%5E%2Fbar" is "bar"';
is $p->get([{'foo^/bar' => 'bar'}], '/0/foo^^^/bar'), 'bar',
'"/0/foo^^^/bar" is "bar"';
is $p->get([{'foo^/bar' => 'bar'}], '/0/foo%5E%5E%5E/bar'), 'bar',
'"/0/foo%5E%5E%5E/bar" is "bar"';
is $p->get([{'foo/bar' => 'bar'}], '/0/foo~1bar'), 'bar',
'"/0/foo~1bar" is "bar"';
is $p->get([{'foo~/bar' => 'bar'}], '/0/foo~0~1bar'), 'bar',
'"/0/foo~0~1bar" is "bar"';
is $p->get(
[{'f^o^o^/b^' => {'a^' => {'r' => 'baz'}}}] => '/0/f^^o^^o^^^/b^^/a^^/r'),
'baz', '"/0/f^^o^^o^^^/b^^/a^^/r" is "baz"';
is $p->get([{'f^o^o^/b^' => {'a^' => {'r' => 'baz'}}}] =>
'%2F0%2Ff%5E%5Eo%5E%5Eo%5E%5E%5E%2Fb%5E%5E%2Fa%5E%5E%2Fr'), 'baz',
'"%2F0%2Ff%5E%5Eo%5E%5Eo%5E%5E%5E%2Fb%5E%5E%2Fa%5E%5E%2Fr" is "baz"';
[{'f~o~o~/b~' => {'a~' => {'r' => 'baz'}}}] => '/0/f~0o~0o~0~1b~0/a~0/r'),
'baz', '"/0/f~0o~0o~0~1b~0/a~0/r" is "baz"';

0 comments on commit f44a48d

Please sign in to comment.