Skip to content

Instantly share code, notes, and snippets.

@seratch
Created October 18, 2011 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save seratch/1295847 to your computer and use it in GitHub Desktop.
Save seratch/1295847 to your computer and use it in GitHub Desktop.
#daimonscala 19-1 "JSON parser" Blank
// obj ::= "{" [members] "}".
// arr ::= "[" [values] "]".
// value ::= obj | arr | stringLiteral | floatingPointNumber | "null" | "true" | "false".
// values ::= value { "," value }.
// members ::= member { "," member }.
// member ::= stringLiteral ":" value.
object Main {
import util.parsing.combinator._
object JSONParser extends JavaTokenParsers {
def obj: Parser[Map[String,Any]]
def parse(json: String): ParseResult[Map[String,Any]] = parseAll(obj, json)
}
def main(args: Array[String]) {
val json = """
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
"""
val result = JSONParser.parse(json)
println(result.get)
// Map("menu" -> Map("id" -> "file", "value" -> "File", "popup" -> Map("menuitem" -> List(Map("value" -> "New", "onclick" -> "CreateNewDoc()"), Map("value" -> "Open", "onclick" -> "OpenDoc()"), Map("value" -> "Close", "onclick" -> "CloseDoc()")))))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment