Revan
Revan

Reputation: 261

spray-json JsString quotes on string values

I am using json-spray. It seems that when I attempt to print a parsed JsString value, it includes book-ended quotes on the string.

val x1 = """ {"key1": "value1", "key2": 4} """
println(x1.asJson)
println(x1.asJson.convertTo[Map[String, JsValue]])

Which outputs:

{"key1":"value1","key2":4}
Map(key1 -> "value1", key2 -> 4)

But that means that the string value of key1 is actually quoted since scala displays strings without their quotes. i.e. val k = "value1" outputs: value1 not "value1". Perhaps I am doing something wrong, but the best I could come up with to alleviate this was the following:

val m = x1.asJson.convertTo[Map[String, JsValue]]
val z = m.map({
    case(x,y) => {
        val ny = y.toString( x => x match {
            case v: JsString =>
                v.toString().tail.init
            case v =>
                v.toString()
        } )
        (x,ny)
    }})

println(z)

Which outputs a correctly displayed string:

Map(key1 -> value1, key2 -> 4)

But this solution won't work for recursively nested JSON. Is there a better workaround?

Upvotes: 9

Views: 8226

Answers (3)

Cubean
Cubean

Reputation: 11

In the new version, there is a little difference:

libraryDependencies ++= "io.spray" % "spray-json_2.12" % "1.3.3"

import spray.json.DefaultJsonProtocol._
import spray.json._

object SprayJson extends ExampleBase {

  private def jsonValue(): Map[String, String] = {
    val x1 = """ {"key1": "value1", "key2": 4} """

    val json = x1.parseJson
    println(json.prettyPrint)

    json.convertTo[Map[String, JsValue]].map(v =>
      (v._1, v._2 match {
        case s: JsString => s.value
        case o => o.toString()
      }))
  }

  override def runAll(): Unit = {
    println(jsonValue())
  }
}

The output:

{
  "key1": "value1",
  "key2": 4
}
Map(key1 -> value1, key2 -> 4)

Upvotes: 1

Yuriy Shinbuev
Yuriy Shinbuev

Reputation: 427

Try this:

import spray.json._
import DefaultJsonProtocol._
val jsString = new JsString("hello")
val string = jsString.convertTo[String]

Upvotes: 17

dvliman
dvliman

Reputation: 606

I ran into exact same problem. Digging through the source code, they are using compactPrint which seems fine. I don't at what point it is bring wrapped with quotes

Upvotes: 0

Related Questions