tags:

views:

2422

answers:

1

I am using JsonResponse to send some JSON to the client. I would like to test that I am building the correct message for a given input, so it seemed natural to me to parse the resulting JSON and validate against a data structure rather than parsing a string by hand.

Lift's JsObj produces a string which uses single quotes. This is valid according to ECMAScript 5th Ed. but not according to the original RFC 4627 by Crockford, though JQuery will handle it fine:

  def tryToParse = {
    val jsObj :JsObj = JsObj(("foo", "bar")); // 1)
    val jsObjStr :String = jsObj.toJsCmd      // 2) jsObjStr is: "{'foo': 'bar'}"
    val result = JSON.parseFull(jsObjStr)     // 3) result is: None

    // the problem seems to be caused by the quotes:
    val works = JSON.parseFull("{\"foo\" : \"bar\"}")  // 4) result is: Some(Map(foo -> bar))
    val doesntWork = JSON.parseFull("{'foo' : 'bar'}") // 5) result is: None
  }

How do I programmatically construct a valid JSON message in Scala/Lift that can also be parsed again?

+3  A: 

It looks like I can get parsing to work using Lift's

net.liftweb.util.JSONParser

rather than Scala's which refuses to parse single quoted JSON strings:

scala> import scala.util.parsing.json.JSON._       
import scala.util.parsing.json.JSON._

scala> val parsed = parseRaw("{\"foo\" : 4 }")
parsed: Option[scala.util.parsing.json.JSONType] = Some(JSONObject(foo -> 4.0))

scala> val notParsed = parseRaw("{'foo' : 4 }")                 
notParsed: Option[scala.util.parsing.json.JSONType] = None

by doing it this way:

val result = JSONParser.parse(jsObjStr)  // 6) result is: Full(Map(foo -> bar))
David Carlson