Kevin Meredith
Kevin Meredith

Reputation: 41909

Escaping JSON's Double-Quotes in Keys and Values?

Is there an equivalent JSON.stringify in Java/Scala?

I'd like to use this function as so:

JSON.stringify( JSON.stringify( { "a" : "have a nice day, \" sir!" } ) )
""{\"a\":\"have a nice day, \\\" sir!\"}""

Upvotes: 0

Views: 1044

Answers (1)

Kevin Meredith
Kevin Meredith

Reputation: 41909

Using spray-json:

scala> import spray.json._
import spray.json._

scala> def stringifyTwice(json: JsValue): String = 
     |   JsString(json.compactPrint).compactPrint
stringify: (json: spray.json.JsValue)String

scala> val obj: JsValue = JsObject("foo" -> JsString("bar"), "bippy" -> JsString("bap \" biz"))
obj: spray.json.JsValue = {"foo":"bar","bippy":"bap \" biz"}

scala> stringifyTwice(obj)
res0: String = "{\"foo\":\"bar\",\"bippy\":\"bap \\\" biz\"}"

Upvotes: 1

Related Questions