scala - Play 2.4.1: How to replace all the occurrences of one or more keys in a JSON tree -


given following json...

{   "id" : "52fe942b790000790079b7d0",   "email" : "joe@domain.com",   "username" : "joe",   "subscriptions" : [     {       "accountid" : "72fe942b790000790079b755",       "name" : "test 1",       "isdefault" : true     },     {       "accountid" : "72fe942b796850790079b743",       "name" : "test 2",       "isdefault" : false     }   ] } 

.. need transform each id objectid required mongodb (i.e. id -> _id \ $oid , accountid -> accountid \ $oid:

{   "_id" : {"$oid" : "52fe942b790000790079b7d0"},   "email" : "joe@domain.com",   "username" : "joe",   "subscriptions" : [     {       "accountid" : {"$oid" : "72fe942b790000790079b755"},       "name" : "test 1",       "isdefault" : true     },     {       "accountid" : {"$oid" : "72fe942b796850790079b743"},       "name" : "test 2",       "isdefault" : false     }   ] } 

up play 2.3.8 used play-json-zipper , updateallkeynodes did trick:

import play.api.libs.json._ import play.api.libs.json.extensions._  json.updateallkeynodes {   case ((_ \ "_id"), value) => "id" -> value \ "$oid"   case ((_ \ "accountid"), value) => "accountid" -> value \ "$oid" } 

unfortunately play 2.4.1 have remove play-json-zipper project because doesn't support new json model.

what correct alternative achieve same result standard play json library?

you can use - , + jsobject.

val json = json.parse("""{"id":"123","a":1}""")  val id = (json \ "id").as[jsstring] // find id val fixed = json.as[jsobject] - ("id") + ("_id", id) // replace 

for more complicated requirements:

json.parse(str) match   case jsobject(j) =>     val newid = jsobject(seq("$old" -> j("id")))     val newss = j("subscriptions") match {       case jsarray(ss) => jsarray(ss.map {         case jsobject(s) =>           val = s("accountid").as[jsstring]           val n = jsobject(seq("$old" -> i))           jsobject(s + ("accountid" -> n))       })     }     jsobject(j - "id" + ("_id" -> newid) + ("subscriptions" -> newss)) } 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -