简体   繁体   中英

Not extracting json properly using json4s

I have a json:

{"key1":["12345"],"key2":[{"key3":"some value"}]}

I need to extract the value for key3

When I am doing compact(render(json \\ "key2" \\ "key3"))

I am getting a string with the square bracket ["some value"]. Please let me know how to get only value as a string.

Here is a way to do so, using the apply method on the JArray :

import org.json4s._
import org.json4s.native.JsonMethods._

val json = parse("""{"key1":["12345"],"key2":[{"key3":"some value"}]}""")
(json \ "key2" )(0) \ "key3"
// res6: JValue = JString("some value")

Try \\\\ which returns all matching fields by name. For example

import org.json4s._
import org.json4s.native.JsonMethods._

object Hello extends App {
  val json = parse("""{"key1":["12345"],"key2":[{"key3":"some value"}]}""")
  println(json \\ "key3")
}

should output JString(some value) .

import org.json4s.jackson.JsonMethods

val x =
  """{"key1":["12345"],"key2":[{"key3":"some value"}]}
    | """
val key3 =  JsonMethods.parse(x) \ "key2" \ "key3"
val list = (key3.values)
println(list)

Would print List(some value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM