Skip to content

Instantly share code, notes, and snippets.

@pstuifzand
Created January 6, 2013 11:22
Show Gist options
  • Save pstuifzand/4466646 to your computer and use it in GitHub Desktop.
Save pstuifzand/4466646 to your computer and use it in GitHub Desktop.
Parsing a JSON string with Marpa.
use strict;
use Marpa::R2;
my $g = Marpa::R2::Scanless::G->new({
action_object => 'main',
default_action => 'do_first_arg',
source => \(<<'END_OF_SOURCE'),
:start ::= string
string ~ '"' in_string '"'
in_string ~ in_string_char*
in_string_char ~ [^"\\]
| '\"'
#| [\\] '"'
| [\\] 'b'
| [\\] 'f'
| [\\] 't'
| [\\] 'n'
| [\\] 'r'
| [\\] 'u' four_hex_digits
| [\\] '/'
| [\\] [\\] # \\ (1)
| '\\' # \\ (2)
| [\x{005c}] [\x{005c}] # \\ (3)
four_hex_digits ~ hex_digit hex_digit hex_digit hex_digit
hex_digit ~ [0-9a-fA-F]
:discard ~ ws
ws ~ [\s]+
END_OF_SOURCE
});
my $string = <<'INPUT';
"hello world\\\""
INPUT
my $re = Marpa::R2::Scanless::R->new({ grammar => $g });
$re->read(\$string);
my $res = $re->value;
print $$res;
sub new {
return bless {}, 'main';
}
sub do_first_arg { shift; return $_[0]; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment