scala - Play Framework: How to sort JSON alphabetically -
given following json...
{ "z": 100, "b": 50, "q": 12 }
how sort keys alphabetically?
simple enough, (obviously) need make sure have jsobject
.
val js = json.parse("""{ "z": 100, "b": 50, "q": 12 }""") val jsobject = js.as[jsobject] // not safe, bear me
the fields stored in field called fields
seq[(string, jsvalue)]
.
scala> jsobject.fields res5: seq[(string, play.api.libs.json.jsvalue)] = listbuffer((z,100), (b,50), (q,12))
we can make new jsobject
same fields, except sorted.
scala> jsobject(jsobject.fields.sortby(_._1)) res6: play.api.libs.json.jsobject = {"b":50,"q":12,"z":100}
earlier, mentioned using as[jsobject]
unsafe, because if our jsvalue
array or string, throw exception. safer way handle jsvalue
here pattern match on jsobject
, sort it, , nothing other type. simple enough create method recursively sorts keys:
def sortjs(js: jsvalue): jsvalue = js match { case jsobject(fields) => jsobject(fields.sortby(_._1).map { case (k, v) => (k, sortjs(v)) }) case _ => js } val js = json.parse("""{ "z": 100, "b": {"k": 1, "j": 3, "i": 98}, "q": 12 }""") scala> sortjs(js) res8: play.api.libs.json.jsvalue = {"b":{"i":98,"j":3,"k":1},"q":12,"z":100}
Comments
Post a Comment