Created
June 10, 2014 14:16
-
-
Save petekneller/f6358b416b449a5c6017 to your computer and use it in GitHub Desktop.
Example JSON parser using Scala parser combinator
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
/* | |
Thx to Albert Latacz for passing this on to me | |
Think its more or less a direct lift from the Artima Programming in Scala book, chapter 33 | |
at http://booksites.artima.com/programming_in_scala_2ed/examples/html/ch33.html | |
*/ | |
import java.io.InputStreamReader | |
import pure.commons.store.FileUtils | |
import scala.util.parsing.combinator._ | |
import scala.util.parsing.input.StreamReader | |
trait JsonParsers extends JavaTokenParsers { | |
def jsonObject: Parser[Any] = "{" ~ repsep(jsonMember, ",") ~ "}" | |
def jsonArray: Parser[Any] = "[" ~ repsep(jsonValue, ",") ~ "]" | |
def jsonMember: Parser[Any] = stringLiteral ~ ":" ~ jsonValue | |
def jsonValue: Parser[Any] = jsonObject | jsonArray | stringLiteral | floatingPointNumber | "null" | "true" | "false" | |
} | |
object JsonParsersExample extends JsonParsers { | |
def main(args: Array[String]) { | |
val startTime = System.currentTimeMillis() | |
parseAll(jsonValue, StreamReader(new InputStreamReader(FileUtils.url("test.json").openStream()))) match { | |
case x:Failure => println(x.toString()) | |
case _ => println("Is ok") | |
} | |
println("Parsed in " + (System.currentTimeMillis() - startTime) + "ms") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment