user504909 user504909 - 3 months ago 34
Scala Question

How to get json parent property instead of taken all of same property name in json4s

I use json4s and scala 2.11.12

the exmaple json is:

{ "name": "joe",
"children": [
{
"name": "Mary",
"age": 5
},
{
"name": "Mazy",
"age": 3
}
]
}


when I want to get the name, instead of get parent name "joe", it give me all names of parents and child by(I use json4s library http://json4s.org/)

compact(render(json \\ "name"))


it return me :

res2: String = {"name":"joe","name":"Mary","name":"Mazy"}

I only need {"name":"joe"}

I only need parent name, How to get only parent name?

Answer
val json = "..."
import org.json4s._
import org.json4s.native.JsonMethods._
val parent: JValue = json \ "name"

The \ method which with the native implementation of JSON4S will be lift-json based, will look up a field value by name inside a JSON object. Note, your json needs to be a JValue before you can do this, so from a val jsonData: String you need to call val json = Json.parse(jsonData) to get the initial JValue.

The double backslash \\ method will find all children of the JSON that have a given property, so that's why you are getting the entire set of JObject matches back.