Jorge Lazo
Jorge Lazo

Reputation: 388

Adding all fields from a Map value to Json in Scala

I have a list of documents, with data in the form of Map[String, Any] so that it can be added to a json object with fields and values respectively. So my code looks something like this when parsing:

val JsonDoc = Json.obj(
      "ORFID" -> doc("ORFID").toString,
      "ORF_len" -> doc("ORF_len").toString,
      "start" -> doc("start").toString,
      "end" -> doc("end").toString
...// more fields
)

However some documents may be missing one of the fields, so I need a more dynamic approach depending on each documents fields, or else an exception is thrown. What would be the best approach for this?

Upvotes: 0

Views: 185

Answers (1)

Edwin
Edwin

Reputation: 836

You could try JsObject instead. Its constructor needs a Seq of tuples which you can get from your map with the method toSeq, this assuming, you want to use the same keys in your json as in the Map.

val jsonDoc = new JsonObj(doc.toSeq)

Upvotes: 2

Related Questions