user504909 user504909 - 1 year ago 187
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

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 Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download