Convert JValue to JSON string
Asked Answered
O

1

5

I want to convert a jvalue to json string. Here is what my code look like:

import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
import org.json4s.DefaultFormats._

 object Json4sTest {

  def main(arg: Array[String]) {
    var json = parse("""{"name":"luca", "id": "1q2w3e4r5t", "age": 26, "inner": { "age": 27 }, "url":"http://    www.nosqlnocry.wordpress.com"}""")
 //   println(json)

    val a: List[Map[String, JValue]] = List(Map("inner/age" -> 35, "age" -> 27), Map("name" -> "foo"))
    val r = jsonFieldUpdater(json, a)
    println(r)

        }


      def jsonFieldUpdater(json: JValue, list: List[Map[String, JValue]]): JValue =
    //
      }
    }

gets me the result as :

JObject(List((name,JString(foo)), (id,JString(1q2w3e4r5t)), (age,JInt(27)), (inner,JObject(List((age,JInt(35))))), (url,JString(http://    www.nosqlnocry.wordpress.com))))

I am looking for a Json String output as :

{"name":"luca", "id": "1q2w3e4r5t", "age": 27, "inner": { "age": 35 }, "url":"http://    www.nosqlnocry.wordpress.com"}
Ovum answered 17/3, 2017 at 11:11 Comment(2)
I was able to use (compact(render(r))).toString() to get this done.But I am not sure if its the right way.Ovum
If my answer was correct, may I suggest to edit title? I think e.g. Convert JValue to it's string representation could be more appropriate. You can also consider marking my answer as correct. If not, just ignore this comment.Hildegardhildegarde
H
7

If you want to print string representation of JValue, you can do it by: println(compact(render(r)))

This way the String received by method compact(render(r)) looks like this:

{"lotto":{"lotto-id":5,"winning-numbers":[2,45,34,23,7,5,3],"winners":[{"winner-id":23,"numbers":[2,45,34,23,3,5]},{"winner-id":54,"numbers":[52,3,12,11,18,22]}]}}

Or you can use println(pretty(render(r))) to obtain pretty String like this:

{
  "lotto":{
    "lotto-id":5,
    "winning-numbers":[2,45,34,23,7,5,3],
    "winners":[{
      "winner-id":23,
      "numbers":[2,45,34,23,3,5]
    },{
      "winner-id":54,
      "numbers":[52,3,12,11,18,22]
    }]
  }
}

Examples used from documentation.

Hildegardhildegarde answered 17/3, 2017 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.