Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#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