2

Given the following sequence of JsValue instances:

[
    { "name":"j3d" },
    { "location":"Germany" }
]

How do I merge them to a single JSON document like this?

{
    "name":"j3d",
    "location":"Germany"
}

Here below is my Scala code:

import play.api.libs.json._

val values = Seq(Json.obj("name":"j3d"), Json.obj("location":"Germany")

how do I merge all the JSON objects in values?

j3d
  • 9,000
  • 18
  • 81
  • 159
  • I think you on right track do this `Json.obj("name"->"j3d","location"->"Germany")` – Yogesh Dec 18 '14 at 13:24
  • [Merge the two objects](http://stackoverflow.com/questions/18498801/how-to-merge-two-json-objects-values-by-keys) – Roger Dec 18 '14 at 13:26
  • Yes I know... but in my real case I have a `Seq[JsValue]` as an input. – j3d Dec 18 '14 at 13:35

1 Answers1

9

You can use a fold and deepMerge:

values.foldLeft(Json.obj())((obj, a) => obj.deepMerge(a.as[JsObject]))
edi
  • 3,084
  • 20
  • 16