2

I'm trying to manipulate a JSON object in Scala using Json4s.

Say my JSON looks like this:

{
  "data": {
    "plan": {
      "itineraries": [
       {
         "startTime": 1494933289000,
         "duration": 2174
       },
       {
         "startTime": 2494933289000,
         "duration": 3174
       }
     ]
    }
  }
}

Say I want to add a field to each itinerary - Like so:

{
  "data": {
    "plan": {
      "itineraries": [
       {
         "startTime": 1494933289000,
         "duration": 2174,
         "id": "1"
       },
       {
         "startTime": 2494933289000,
         "duration": 3174,
         "id": "2"
       }
     ]
    }
  }
}

How do I do that?

2
  • maybe you can find answer in stackoverflow.com/a/21469460/5160111 Commented May 31, 2017 at 8:47
  • It's not the same thing :-/ I'm trying to add a unique value to each element in an array. That example is just adding a node to another node Commented May 31, 2017 at 8:55

2 Answers 2

4

Have reader case class : ItineraryReads(startTime, duration)

Writer case class : ItineraryWrites(startTime, duration, id)

def mapToWrites(obj : List[ItineraryReads]) = {

obj.map(o => ItineraryWrites(o.startTime, o.duration, (obj.indexOf(o)) + 1))

}

This should work. Write it out as a list of ItineraryWrites :)

Sign up to request clarification or add additional context in comments.

1 Comment

you might like obj.zipWithIndex.map { case (itinerary, index) => ..}
1

transformField can be used to cover this situation with merge:

  val t = parse(s).transformField {
    case JField("itineraries", JArray(arr)) => // pattern match in there, more type safe
      val r = arr.zipWithIndex.map(f => f._1 merge JObject("id" -> JInt(f._2 + 1)))
      ("itineraries", r)
  }
  println(compact(render(t)))
  > {"data":{"plan":{"itineraries":[{"startTime":1494933289000,"duration":2174,"id":1},{"startTime":2494933289000,"duration":3174,"id":2}]}}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.