Created
June 3, 2013 10:10
-
-
Save martintrojer/5697273 to your computer and use it in GitHub Desktop.
parser combinators
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
{ | |
"address book" : { | |
"name" : "John Smith", | |
"address" : { | |
"street" : "10 Market Street", | |
"city" : "San Francisco, CA", | |
"zip" : 94111 | |
}, | |
"phone numbers" : [ | |
"408 338-4238", | |
"408 111-6892" | |
] | |
} | |
} |
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
import scala.util.parsing.combinator._ | |
class JSON extends JavaTokenParsers { | |
def obj: Parser[Map[String, Any]] = "{" ~> repsep(member, ",") <~ "}" ^^ (Map() ++ _) | |
def arr: Parser[List[Any]] = "[" ~> repsep(value, ",") <~ "]" | |
def member: Parser[(String, Any)] = stringLiteral ~ ":" ~ value ^^ | |
{ case name ~ ":" ~ value => (name, value) } | |
def value: Parser[Any] = obj | | |
arr | | |
stringLiteral | | |
floatingPointNumber ^^ (_.toDouble) | | |
"null" ^^ (_ => null) | | |
"true" ^^ (_ => true) | | |
"false" ^^ (_ => false) | |
} |
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
import java.io.FileReader | |
object ParseJSON extends JSON with App { | |
val reader = new FileReader("addr.json") | |
println(parseAll(value, reader)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment