Skip to content

Instantly share code, notes, and snippets.

@Boldewyn
Created January 26, 2017 20:51
Show Gist options
  • Save Boldewyn/68973d3a076ae513830e9e119f183f80 to your computer and use it in GitHub Desktop.
Save Boldewyn/68973d3a076ae513830e9e119f183f80 to your computer and use it in GitHub Desktop.
A JSON grammar for nearley
@{%
const merge = d => d.join('');
const nth = n => d => d[n];
%}
@builtin "whitespace.ne"
json -> _ object _ {% nth(1) %}
| _ array _ {% nth(1) %}
object -> "{" _ "}" {% () => { return {}; } %}
| "{" _ members _ "}" {% nth(2) %}
members -> pair {% id %}
| pair _ "," _ members {% d => {
for (var key in d[0]) {
if (d[0].hasOwnProperty(key)) {
d[4][key] = d[0][key];
}
}
return d[4];
} %}
pair -> string _ ":" _ value {% d => { var x = {}; x[d[0]] = d[4]; return x; } %}
array -> "[" _ "]" {% () => [] %}
| "[" _ elements _ "]" {% nth(2) %}
elements -> value {% d => [d[0]] %}
| value _ "," _ elements {% d => [].concat(d[0], d[4]) %}
value -> string {% id %}
| number {% d => parseFloat(d[0]) %}
| object {% id %}
| array {% id %}
| "true" {% () => true %}
| "false" {% () => false %}
| "null" {% () => null %}
string -> "\"\"" {% () => "" %}
| "\"" chars "\"" {% nth(1) %}
chars -> char {% id %}
| char chars {% merge %}
char -> [^"\\\x00-\x1F\x7F] {% id %} # any Unicode character except " or \ or control character
| "\\\"" {% () => "\"" %}
| "\\\\" {% () => "\\" %}
| "\\/" {% () => "/" %}
| "\\b" {% () => "\b" %}
| "\\f" {% () => "\f" %}
| "\\n" {% () => "\n" %}
| "\\r" {% () => "\r" %}
| "\\t" {% () => "\t" %}
| "\\u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]
{% d => String.fromCharCode(d[1] + d[2] + d[3] + d[4]) %}
number -> int {% id %}
| int frac {% merge %}
| int exp {% merge %}
| int frac exp {% merge %}
int -> digit {% id %}
| digit19 digits {% merge %}
| "-" digit {% merge %}
| "-" digit19 digits {% merge %}
frac -> "." digits {% merge %}
exp -> e digits {% merge %}
digits -> digit {% id %}
| digit digits {% merge %}
digit -> [0-9] {% id %}
digit19 -> [1-9] {% id %}
e -> "e" {% id %}
| "e+" {% id %}
| "e-" {% id %}
| "E" {% id %}
| "E+" {% id %}
| "E-" {% id %}
@Boldewyn
Copy link
Author

Usage:

npm install -g nearley
nearleyc -o json.js json.ne
nearley-test json.js < /your/nearest/package.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment