Failed to Extract from List

23 views
Skip to first unread message

Chetan Conikee

unread,
Jul 22, 2014, 3:08:14 AM7/22/14
to raptur...@googlegroups.com



I am attempting to extract the element of a List via Pattern matching.
I would NOT want to use case classes as we do not have the structure of the JSON defined upfront.

I attempted to execute the following based of your json-test example.

I am not sure if I am doing this right, but can you please point me to the right way of extracting the attributes as a tuple

val source1 = json"""{
"string": "Hello",
"int": 42,
"double": 3.14159,
"boolean": true,
"list": [{ "alpha": "test1", "beta": 1 },{ "alpha": "test2", "beta": 2 },{ "alpha": "test3", "beta": 3 }],
"foo": { "alpha": "test", "beta": 1 },
"bar": { "foo": { "alpha": "test2", "beta": 2 }, "gamma": 2.7 }
}"""

//works
source1 match { 
case json""" {"list" : $l } """ => l }

//Fails
source1 match { 
case json""" {"list" : [{"alpha" : $a}] } """ => a }

//Fails
source1 match { 
case json""" {"list" : [{"alpha" : $a, "beta" : $b }] } """ => List[(a.as[String],b.as[Long])] }

Jon Pretty

unread,
Jul 22, 2014, 8:34:04 PM7/22/14
to raptur...@googlegroups.com
Hi Chetan,

As I mentioned in the GitHub issue, extracting into arrays isn't currently supported, but I'm starting to think it should be.I will explore this possibility tomorrow.

You can do the following with your example, though:

  val elements = source1.list.as[List[Json]]
  val pairs = elements map { e => e.alpha.as[String] -> e.beta.as[Long] }

Note that in your last example, even with support for array extraction, this wouldn't match anyway: the lengths of the arrays would have to match in order for us to be able to uniquely bind to the variables $a and $b.

Cheers,
Jon

Chetan Conikee

unread,
Jul 23, 2014, 9:20:32 AM7/23/14
to raptur...@googlegroups.com
Thanks for the reply Jon. Appreciate it.
In order to align/match the length of arrays of attributes belonging to the same object, would it make sense to bind the the tuples to option type ?

Jon Pretty

unread,
Jul 25, 2014, 3:42:16 AM7/25/14
to raptur...@googlegroups.com
Hi Chetan,

I'm not sure I follow... Can you give me an example of what you mean?

There might be a few other possibilities about how we extract values. I'm not sure if you spotted my implementation in Rapture JSON 0.10 (not released yet) which allows you to force exact matching on entire arrays, rather than (the default) of just matching the specified elements. But I could perhaps introduce other configuration parameters, if there are other ways the matching/extraction could work.

Cheers,
Jon
Reply all
Reply to author
Forward
0 new messages