Charles Daily
Charles Daily

Reputation: 375

How do you grab an element in a JSON tree without an explicit name in Play 2.0?

I've been working through parsing .json files in a Play 2.0 project and there is one thing I can't figure out. Here is a snippet from the online docs:

{
  "users":[
    {
      "name": "Bob",
      "age": 31.0,
      "email": "[email protected]"
    },
    {
      "name": "Kiki",
      "age":  25.0,
      "email": null
    }
  ]
}

What I want to know is, how do I grab one whole user? The problem is that I can't figure out how to reference the grouping of parameters that represents a single user. I've tried something like

( json \\ "users" ) 

which just gives all the users as a single element in a list, and I've tried something like

( json \ "users" \ (user)(0)) 

but it seems I have to define 'user' and I have no idea what would be appropriate for that.

Better yet, is there a way to grab all the customers in a list? Or even just iterate over the tree and hit upon each user so I can access all the information of a specific user at once?

Upvotes: 0

Views: 539

Answers (2)

Alex Varju
Alex Varju

Reputation: 2922

If you already know that the JSON contains a list of objects, you can ask for that element to be extracted as one, using as[List[JsObject]].

For example:

val str = """{
  "users":[
    {
      "name": "Bob",
      "age": 31.0,
      "email": "[email protected]"
    },
    {
      "name": "Kiki",
      "age":  25.0,
      "email": null
    }
  ]
}"""

val json = Json.parse(str)
val users = (json \ "users").as[List[JsObject]]
users.foreach { user =>
  println("user: " + user)
}

Generates:

user: {"name":"Bob","age":31.0,"email":"[email protected]"}
user: {"name":"Kiki","age":25.0,"email":null}

Each of these list elements support the same operators as the original JSON object, so you can extract individual values using (user \ "name").as[String], etc.

Upvotes: 1

v6ak
v6ak

Reputation: 1656

Jerkson JSON (the JSON library used in Play!) supports this way:

(json \ "users")(0)

If you want to iterate, you can cast it to JArray (and possibly check the type) and call the elements method:

(json \ "users").asInstanceOf[JArray].elements foreach {
    ...
}

There is probably no better way: https://github.com/codahale/jerkson/blob/master/src/main/scala/com/codahale/jerkson/AST.scala

Upvotes: 0

Related Questions