[2.1-RC-2 Scala] parse simple json string from array of objects

855 views
Skip to first unread message

oblivion

unread,
Jan 17, 2013, 4:10:51 AM1/17/13
to play-fr...@googlegroups.com
How do I parse a Json-String existing as an Array of Objects WITHOUT creating Readers and Writers?

[
{"key": "value1"},
{"key": "value2"}
]

I would like to end up with a List of Maps or anything similar:

Seq(Map("key" -> "value1"), Map("key" -> "value2"))

Json.parse(json) just returns a JsValue which cannot be iterated upon, so an array-walk is not possible?

With lift-json you could just write:

val prizes = for {
    JObject(str) <- json.parse(json)
    JField("key", JString(key)) <- str
  } yield MyObj(key)

oblivion

unread,
Jan 17, 2013, 6:21:32 AM1/17/13
to play-fr...@googlegroups.com
The Play 2.0 docs only mention what method to use to parse a String:

val json: JsValue = Json.parse(jsonString)

But there is no way of finding out how to parse an Array of Objects.

Also I am on 2.1 so there is no docs yet on how to accomplish this?

Pascal Voitot Dev

unread,
Jan 17, 2013, 6:29:50 AM1/17/13
to play-fr...@googlegroups.com
I'm not sure to understand your problem but this should do what you expect:

scala> val m = Json.parse(jsonString).as[Seq[Map[String, String]]]
m: Seq[Map[String,String]] = List(Map(key -> value1), Map(key -> value2))



--
 
 

oblivion

unread,
Jan 17, 2013, 7:08:12 AM1/17/13
to play-framework
Thanks, I was missing the "as" method.

I'm wondering how I could get it to work if I mix integers with
strings in the json-string:

as[Seq[Map[String, Any]] does not work.

On Jan 17, 12:29 pm, Pascal Voitot Dev <pascal.voitot....@gmail.com>
wrote:

Pascal Voitot Dev

unread,
Jan 17, 2013, 8:03:56 AM1/17/13
to play-fr...@googlegroups.com
On Thu, Jan 17, 2013 at 1:08 PM, oblivion <recalc...@web.de> wrote:
Thanks, I was missing the "as" method.

I'm wondering how I could get it to work if I mix integers with
strings in the json-string:

as[Seq[Map[String, Any]] does not work.

yes it doesn't work because there is no way to know how to read Any in a static-typed api.

for this, it's to go through a JsObject which is a really good heterogenous map.

obj =  ...as[Seq[JsObject]]

obj.fields => Seq[(String, JsValue)]

Pascal

 
--



Reply all
Reply to author
Forward
0 new messages