score:2
Accepted answer
Taking following as input (where attr
is an array of objects):
val input =
"""
|{
| "id":123,
| "students":[
| {
| "collected":{
| "field":"field_1"
| },
| "attr":[{
| "name":"test_name",
| "age":"17",
| "color":"blue"
| }]
| },
| {
| "collected":{
| "field":"field_2"
| },
| "attr":[{
| "name":"test_name2",
| "age":"18",
| "color":"red"
| }]
| }
| ]
|}
|""".stripMargin
We can apply following transformer to get the required results:
val attrTransformer = (__ \ "attr").json.update {
__.read[JsArray].map {
case JsArray(values) =>
val updatedValues = values.map { x =>
JsObject(x.as[JsObject].fields.map { z =>
val (key, value) = z
(key, JsString(key + value.as[String]))
})
}
JsArray(updatedValues)
}
}
val transformer = (__ \ "students").json.update(Reads.list(attrTransformer).map(x => JsArray(x)))
val output = json.transform(transformer).get
The output after transformation will be:
{
"students" : [ {
"collected" : {
"field" : "field_1"
},
"attr" : [ {
"name" : "nametest_name",
"age" : "age17",
"color" : "colorblue"
} ]
}, {
"collected" : {
"field" : "field_2"
},
"attr" : [ {
"name" : "nametest_name2",
"age" : "age18",
"color" : "colorred"
} ]
} ],
"id" : 123
}
Old Answer
Considering the below input (where attr
is not an array of JsObject
):
val input =
"""
|{
| "id":123,
| "students":[
| {
| "collected":{
| "field":"field_1"
| },
| "attr":{
| "name":"test_name",
| "age":"17",
| "color":"blue"
| }
| },
| {
| "collected":{
| "field":"field_2"
| },
| "attr":{
| "name":"test_name2",
| "age":"18",
| "color":"red"
| }
| }
| ]
|}
|""".stripMargin
A simple solution would be to create a new JsObject with updated values as below. (without any validations)
val students = (Json.parse(input) \ "students").as[JsArray]
val requiredStudents = students.value.map { student =>
val attr = student \ "attr"
val updatedAttributes = attr.get.as[JsObject].fields.map { x =>
val (key, value) = x
(key, JsString(key + value.as[String]))
}
val requiredStudent = student.as[JsObject] ++ Json.obj("attr" -> JsObject(updatedAttributes))
requiredStudent
}
requiredStudents.foreach(println)
The output for each student will be as follows:
{"collected":{"field":"field_1"},"attr":{"name":"nametest_name","age":"age17","color":"colorblue"}}
{"collected":{"field":"field_2"},"attr":{"name":"nametest_name2","age":"age18","color":"colorred"}}
Source: stackoverflow.com
Related Query
- How to update each field in a list using Play json in Scala
- How to update a nested json using scala play framework?
- How to convert list data into Json in scala using play framework?
- How to load JSON file using Play with Scala
- How to convert casbah mongodb list to json in scala / play
- How to parse json list or array in scala for play framework 2.2
- How to read json array in scala using the Play framework
- Using Gradle, how can I list just the JSON library of the Play framework as a dependency?
- How do I write a query for mongodb using the casbah driver for scala that uses a substring and checks if the field is in a list of supplied values?
- How to get rid of extra escape characters while doing json transformation using scala play framework?
- How to replace value in json using scala play json
- How to convert json file to List using scala
- How to serialize a java.util.Map[String, Object] to JSON in Scala using Play 2.3.9?
- How to serialize a Scala Collection List into json using Gson lib
- How to read list of string from JSON file using Scala
- Scala - How to Split all List of List Json Nodes using json-path
- Convert List to a specific JSON format in Play framework using Scala
- How to update a mongo record using Rogue with MongoCaseClassField when case class contains a scala Enumeration
- How to parse JSON in Scala using standard Scala classes?
- Scala 2.10 reflection, how do I extract the field values from a case class, i.e. field list from case class
- How to respond with a pretty-printed JSON object using play framework?
- How to create a Row from a List or Array in Spark using Scala
- Using Scala 2.10 reflection how can I list the values of Enumeration?
- How to show images using Play framework and Scala in the view page
- How to add a json object in to a json array using scala play?
- Scala Play - How to convert a list of Scala Strings into an Array of javascript Strings (avoiding the " issue)?
- How to modify previous line in REPL - scala to modify the typing errors to save time compare to entering each line using up/down arrows
- How to read json data using scala from kafka topic in apache spark
- Scala + Play Framework + Slick - Json as Model Field
- How can I deserialize from JSON with Scala using *non-case* classes?
More Query from same tag
- Reducing a String causing compile time error?
- Having trouble with defining subclass function
- Spark submit in Azure Data Factory
- Does extending a class in scala inherits auxilary constuctor also?
- How do I remove the proper subsets from a list of sets in Scala?
- scala: Moking my scala Object that has external dependency
- Unable to Analyse data
- Does Scalatest have any support for assumptions?
- How to use group by using multiple keys?
- How to update a nested json using scala play framework?
- Explode array of structs to columns in Spark
- When is case syntactically significant?
- How to update few records in Spark
- How to write in Scala shortly "filter first/last n elements satisfying a given function"?
- Is class parameters with the option type need not to pass a value?
- sbt.ResolveException unresolved dependency
- How to assert 2 scala objects containing list in Scala test?
- Share database code between akka sbt-project and scala-play project
- Creating Akka project in OSGi
- Passing Scala Object/companion object as parametric type
- "Method mapping in object Forms" Error
- Scala equivalent for 'matches' regex method?
- What is the real world example of Scala's Partially applied Function
- Does Scala achieve good performance on Android? (June 2011)
- Firebase and Play Framework (Scala) is it possible?
- Processing JSON containing nested entities using Spark Structured Streaming
- add a prefix to each line of the log with the application name
- Using type parameters and mixins in Scala
- Work on list of tuples in Scala - part 2
- Scala async calculation exercise