Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding field to a json using Circe

I am going through the Circe documentation and can't figure out how to handle the following.

I would simply like to add a field with an object inside the main JSON object.

{
  Fieldalreadythere: {}
  "Newfield" : {}
}

I just want to add the Newfield in the object. To give a bit of context I am dealing with Json-ld. I just want to add a context object. @context: {}

See example below:

{
  "@context": {
    "@version": 1.1,
    "xsd": "http://www.w3.org/2001/XMLSchema#",
    "foaf": "http://xmlns.com/foaf/0.1/",
    "foaf:homepage": { "@type": "@id" },
    "picture": { "@id": "foaf:depiction", "@type": "@id" }
  },
  "@id": "http://me.markus-lanthaler.com/",
  "@type": "foaf:Person",
  "foaf:name": "Markus Lanthaler",
  "foaf:homepage": "http://www.markus-lanthaler.com/",
  "picture": "http://twitter.com/account/profile_image/markuslanthaler"
}

I would like to add the context object.

How can I do that with Circe? The example in the official documentation mostly talk about modifying the value, but nothing to actually add a field and so on.

like image 453
MaatDeamon Avatar asked Dec 08 '18 10:12

MaatDeamon


2 Answers

Take a look at JsonObject. There is +: method that does what you want.

Here's a simple example:

import io.circe.generic.auto._
import io.circe.parser
import io.circe.syntax._

object CirceAddFieldExample extends App {
    val jsonStr = """{
       Fieldalreadythere: {}
    }"""
    val json = parser.parse(jsonStr)
    val jsonObj = json match {
       case Right(value) => value.asObject
       case Left(error) => throw error
    }
    val jsonWithContextField = jsonObj.map(_.+:("@context", contextObj.asJson))
}
like image 84
Tarang Bhalodia Avatar answered Sep 21 '22 14:09

Tarang Bhalodia


You can use the deepMerge method to add two Json together.

Assuming an encoder is available for your context class:

val contextJson: Json = Map("@context" -> context).asJson
val result: Json = existingJson.deepMerge(contextJson)
like image 33
Callum Avatar answered Sep 22 '22 14:09

Callum