scala - how to sort JsArrays with play-json -
scala - how to sort JsArrays with play-json -
simple question:
how can 1 utilize play-json (2.3.x) sort jsarrays in jsvalue (recursively)?
my usecase:consider app uses set[string]
internally, , when info requested, output json serialize set json array. order not important.
now, if 1 wants write tests cover functionality, since order of items not of import (it set after all. internally, , conceptually), , want check returned should, may want compare response json "expected" json object create explicitly.
for exact reason, want sort json arrays, , compare jsvalue
's. how 1 write such transformer?
i have managed write transformer answers needs, won't sort every jsarry
in jsvalue
. i'll post here, since might useful others, not asking for.
val jsonsorttransformer = (__ \ 'fields).json.update( reads.jsobjectreads.map{ case jsobject(xs) => jsobject( xs.map{ case (n,jv) => { n -> (jv match { case jsarray(arr) if arr.forall(_.isinstanceof[jsstring]) => jsarray(arr.sortby(_.as[string])) case _ => jv }) } } ) } )
you can utilize value
property on jsarray
seq[jsvalue]
, sort arbitrarily, , recreate jsarray
. example:
scala> myjsarray play.api.libs.json.jsarray = ["11","4","5","1","22","2"] scala> jsarray(myjsarray.value.sortby(_.as[jsstring].value.toint)) play.api.libs.json.jsarray = ["1","2","4","5","11","22"]
if you're doing trying compare actual , expected values of know set, can utilize value
on both properties, build set
, check equality:
set(actual.value: _*) == set(expected.value: _*)
or sort them both:
val sortedseq: jsarray => seq[string] = array => array.value.map(_.tostring).sorted sortedseq(actual) == sortedseq(expected)
to recursively sort jsarrays
in arbitrary jsvalue
, might like:
def sortarrays(json: jsvalue): jsvalue = json match { case jsobject(obj) => jsobject(obj.tomap.mapvalues(sortarrays(_)).tolist) case jsarray(arr) => jsarray(arr.map(sortarrays).sortby(_.tostring)) case other => other } scala> myobj play.api.libs.json.jsvalue = {"a":[2,1],"b":[{"c":[3,2]},{"d":[4,3]}],"e":{"f":[5,4]}} scala> sortarrays(myobj) play.api.libs.json.jsvalue = {"a":[1,2],"b":[{"c":[2,3]},{"d":[3,4]}],"e":{"f":[4,5]}}
json scala playframework
Comments
Post a Comment