score:3
Accepted answer
Have a look at ScalaJsonTransformers. You can create a transformer that creates the normalised field from a string data value and use it to, erm, transform your original Format
to a new Writes
. Here's a slightly simplified example that could doubtless be improved (you'll want to check various edge cases):
case class ChecklistColumn(kind: String, descriptor: String, data: JsValue)
// The original format.
val checklistFormat: Format[ChecklistColumn] = (
(__ \ "kind").format[String] and
(__ \ "descriptor").format[String] and
(__ \ "data").format[JsValue]
)(ChecklistColumn.apply, unlift(ChecklistColumn.unapply))
// A transformer that looks for a "data" field with a string
// value and adds the normalized_data field if it finds one.
val checklistTransformer: Reads[JsObject] = JsPath.json.update(
(__ \ "data").read[String].flatMap (
str => (__ \ "normalized_data").json.put(JsString(str + "!!!"))))
// A new derived Writes which writes the transformed value if
// the transformer succeeds (a data string), otherwise the
// original value.
implicit val checklistWrites: Writes[ChecklistColumn] = checklistFormat
.transform (js => js.transform(checklistTransformer).getOrElse(js))
That gives me:
Json.prettyPrint(Json.toJson(ChecklistColumn("a", "b", JsNumber(1))))
// {
// "kind" : "a",
// "descriptor" : "b",
// "data" : 1
// }
Json.prettyPrint(Json.toJson(ChecklistColumn("a", "b", JsString("c"))))
// {
// "kind" : "a",
// "descriptor" : "b",
// "data" : "c",
// "normalized_data" : "c!!!"
// }
Source: stackoverflow.com
Related Query
- Play Scala JSON - conditionally add field to JSON object in Writes
- Play Framework - add a field to JSON object
- Add a Json object to JSON Array using scala play
- add field conditionally after traversing all nodes in JSON Circe Scala
- How to implement implicit Json Writes of embedded object in Play Framework 2.x
- How to add a json object in to a json array using scala play?
- Scala + Play Framework + Slick - Json as Model Field
- Play Scala JSON body parser default value field
- Play 2.1 JSON to Scala object
- Using multiple Writes with Play JSON to render different views of an object
- Scala - JSON object is polymorphic on a field type
- Scala Compiler (2.11.7) anomaly with Play JSON Writes
- Add field to existing JSON object with sprayJSON (scala)
- scala play json reads for a seal trait or enum type object
- Play Json add field which is not present in class
- How to update each field in a list using Play json in Scala
- Serialize set to json with a custom Writes in Scala Play 2.4
- Converting a nested scala object into a JSON string using Play JSON
- Ignore JSON field Play Controller Scala
- Play Json Writes: Scala Seq to Json Object
- Expose only field subset in REST JSON Service. Play framework, scala
- Play Framework 2.3 Scala - Serialize nested objects to JSon with implicit Writes converters
- Play framework scala form object for password field binding?
- Deserialize json field from a complex object in scala
- How to add an additional json item per object in scala
- Json to Scala case class object - handling special characters in field names
- Scala : Converting object having UUID field to Json returns blank
- Scala Play Json implicit writes type mismatch
- Play Scala JSON Writes & Inheritance
- How to implement implicit Json Writes of Future object in Play Framework 2.x
More Query from same tag
- Filtering After a Specific Date Spark
- How to pass variable of one function to another function with return type using Scala
- Assign same value to multiple variables in Scala
- Pattern match for variable in scope (Scala)
- How to use where operator in ReactiveMongo?
- Scala Seq GroupBy with Future
- Spark Dataframe:Row object separator
- Control dependency loading ambiguity on SBT multi-project
- How do I run sbt test with scalatest? I had an error: object scalatest is not a member of package org
- Parsing json collection using play scala reads
- How to handle unassigned IDs with anorm?
- Run a function in scala with a list as input
- Connection between kafka and spark : Failed to find data source : kafka
- SBT not loading properly in Intellij-Idea (no SBT external Imports)
- Scala self-type and generic class
- How to use Scala to partition data into buckets for further processing
- Using Sparksql to union two columns with null value in either of them
- Why don't scala collections have any human-readable methods like .append, .push, etc
- what's a simple concise way to get the tail of a list iff it exists?
- How to generate json string if the `Json.obj` contains a `None` value?
- Spark nested complex dataframe
- Interchangeable menu in Scala Play
- custom partitioner in apache spark
- how to use compound index in mongodb using java/scala
- Play Websocket sample - Only one Akka actor?
- Last unique entries above current row in Spark
- Exception in thread "main" java.lang.IllegalArgumentException: Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':
- Why can't I reuse "unapply" without repeating the method signature
- How to revert XML escaped characters (XML unescape)?
- By-name parameter in Scala