Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Created June 3, 2013 10:10
Show Gist options
  • Save martintrojer/5697273 to your computer and use it in GitHub Desktop.
Save martintrojer/5697273 to your computer and use it in GitHub Desktop.
parser combinators
{
"address book" : {
"name" : "John Smith",
"address" : {
"street" : "10 Market Street",
"city" : "San Francisco, CA",
"zip" : 94111
},
"phone numbers" : [
"408 338-4238",
"408 111-6892"
]
}
}
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)
}
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