Created
November 5, 2019 00:36
-
-
Save aod/2abc1b0697f6f45cd719d8bd8053aa3a to your computer and use it in GitHub Desktop.
JSON parser example - PEG.js
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
JSON | |
= _ v:Value _ { return v } | |
Value | |
= Object | |
/ Number | |
/ StringLiteral | |
/ Array | |
/ Boolean | |
/ Null | |
Null | |
= "null" { return null } | |
Boolean | |
= "true" { return true } | |
/ "false" { return false } | |
Object | |
= "{" _ | |
keyValues:( | |
p:Pair _ ","? _ { return p } | |
)+ | |
_ "}" | |
{ return keyValues.reduce((obj, {k,v}) => ({...obj, [k]: v}), {}) } | |
Pair | |
= k:StringLiteral _ ":" _ v:Value { return { k, v } } | |
Array | |
= "[" _ | |
v:( | |
Value _ ","? _ | |
)+ | |
_ "]" | |
{ return v.map(v => v[0])} | |
StringLiteral | |
= "\\"" | |
s:(_? v:String _? { return text() })+ | |
"\\"" | |
{ return s.join(" ") } | |
String | |
= $ [a-z0-9]+ | |
Number | |
= "-"? [0-9]+ ("." [0-9]+)? { return Number(text())} | |
_ | |
= (_S*)? | |
_S | |
= " " | |
/ "\\r"? "\\n" | |
/ "\\t" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment