Created
January 26, 2017 20:51
-
-
Save Boldewyn/68973d3a076ae513830e9e119f183f80 to your computer and use it in GitHub Desktop.
A JSON grammar for nearley
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@{% | |
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 %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: