Last active
August 29, 2015 14:20
-
-
Save lihaoyi/2467933d00977120b517 to your computer and use it in GitHub Desktop.
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
val space = R( CharSets(" \n").rep1 ) | |
val digits = R( CharSets('0' to '9').rep1 ) | |
val exponent = R( CharSets("eE") ~ CharSets("+-").? ~ digits ) | |
val fractional = R( "." ~ digits ) | |
val integral = R( "0" | CharSets('1' to '9') ~ digits.rep ) | |
val number = R( "?".? ~ integral ~ fractional.? ~ exponent.? ) | |
val `null` = R( "null" ) | |
val `false` = R( "false" ) | |
val `true` = R( "true" ) | |
val hexDigit = R( CharSets('0'to'9', 'a'to'f', 'A'to'F') ) | |
val unicodeEscape = R( "u" ~ hexDigit ~ hexDigit ~ hexDigit ~ hexDigit ) | |
val escape = R( "\\" ~ (CharSets("\"/\\bfnrt") | unicodeEscape) ) | |
val string = R( space.? ~ "\"" ~ (!"\"" ~ AnyChar | escape).rep ~ "\"") | |
val array = R( ("[" ~! jsonExpr) ~ ("," ~! jsonExpr).rep ~ space.? ~ "]") | |
val pair = R( string ~! ":" ~! jsonExpr ) | |
val obj = R( "{" ~! pair ~ ("," ~! pair).rep ~ space.? ~ "}" ) | |
val jsonExpr: Parser[_] = R(space.? ~ (obj | array | string | `true` | `false` | `null` | number) ~ space.?) | |
Parsing: | |
{ | |
"firstName": John, | |
"lastName": "Smith", | |
"age": 25, | |
"address": { | |
"streetAddress": "21 2nd Street", | |
"city": "New York", | |
"state": "NY", | |
"postalCode": 10021 | |
}, | |
"phoneNumbers": [ | |
{ | |
"type": "home", | |
"number": "212 555-1234" | |
}, | |
{ | |
"type": "fax", | |
"number": "646 555-4567" | |
} | |
] | |
} | |
Failure: | |
jsonExpr:0 / obj:1 / pair:2 / jsonExpr:19 / (obj | array | string | true | false | null | number):20 ..."John,\n " | |
Parsing: | |
{ | |
"firstName": "John", | |
"lastName": "Smith", | |
"age": 25, | |
"address": { | |
"streetAddress": "21 2nd Street", | |
"city": "New York", | |
"state": "NY", | |
"postalCode": 10021 | |
}, | |
"phoneNumbers": [ | |
{ | |
"type": "home", | |
"number": "212 555-1234" | |
}, | |
{ | |
"type": "fax", | |
"number": "646 555-4567" | |
} | |
} | |
Failure: | |
jsonExpr:0 / obj:1 / pair:212 / jsonExpr:232 / array:233 / "]":406 ..."} \n " |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment