0

1.Input is JSON file that contains multiple records. Example:

[ {"user": "user1", "page": 1, "field": "some"}, {"user": "user2", "page": 2, "field": "some2"}, ... ]

2.I need to load each record from the file as a Document to MongoDB collection. Using casbah for interacting with mongo, inserting data may look like:

  def saveCollection(inputListOfDbObjects: List[DBObject]) = {
    val xs = inputListOfDbObjects
    xs foreach (obj => {
    Collection.save(obj)
  })

Question: What is the correct way (using scala) to parse JSON to get data as List[DBObject] at output?

Any help is appreciated.

1 Answer 1

0

You could use the parser combinator library in Scala.

Here's some code I found that does this for JSON: http://booksites.artima.com/programming_in_scala_2ed/examples/html/ch33.html#sec4

Step 1. Create a class named JSON that contains your parser rules:

import scala.util.parsing.combinator._

class JSON extends JavaTokenParsers {   

  def value : Parser[Any] = obj | arr | 
                        stringLiteral | 
                        floatingPointNumber | 
                        "null" | "true" | "false"

  def obj   : Parser[Any] = "{"~repsep(member, ",")~"}"

  def arr   : Parser[Any] = "["~repsep(value, ",")~"]"

  def member: Parser[Any] = stringLiteral~":"~value
}

Step 2. In your main function, read in your JSON file, passing the contents of the file to your parser.

import java.io.FileReader

object ParseJSON extends JSON {
    def main(args: Array[String]) {
        val reader = new FileReader(args(0))
        println(parseAll(value, reader))
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's a good idea to put the code into your answer. Links break all the time, which means your answer would no longer work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.