Reputation: 186
I am trying to merge together multiple JObjects to become one single JObject. I have a list of JObjects that I am trying to iterate over and merge each of them into one object, essentially creating one large json object.
The below works fine, however when in a list it doesn't work. I know im doing something wrong but not sure what?
val obj1: JObject = RancherHelper.convertToJObject(containers.head)
val obj2: JObject = RancherHelper.convertToJObject(containers(1))
val obj3: JObject = RancherHelper.convertToJObject(containers(2))
val x: JObject = obj1 merge obj2 merge obj3
This doesn't work:
def mergeJObjects(containers: List[JObject]): JObject = {
val fullJsonObject: JObject = JObject()
val singleObject = for{
container <- containers
fullObj = fullJsonObject.merge(container)
} yield fullObj
fullJsonObject
}
Upvotes: 1
Views: 1093
Reputation: 2582
Instead of mapping over the list, fold it:
def mergeJObjects(containers: List[JObject]): JObject = {
containers.foldLeft(JObject())((merged, next) => merged.merge(next))
}
What you have written above is syntactic sugar for this:
val fullJsonObject = JObject()
val singleObject = containers.map { container =>
val fullObj = fullJsonObject.merge(container)
fullObj
}
fullJsonObject
Essentially, you are mapping over the containers list, and for each container you are merging it with an empty JSON object (fullJsonObject
). Therefore singleObject
is no different from containers
; it is a list of your original JSON objects. Moreover, since fullJsonObject
is an immutable empty JObject
, you are simply returning the empty JSON object at the end of your method.
Upvotes: 2