1

I have a JSON string as the following:

{
"cars": {
    "Nissan": [
        {"model":"Sentra", "doors":4},
        {"model":"Maxima", "doors":4},
        {"model":"Skyline", "doors":2}
    ],
    "Ford": [
        {"model":"Taurus", "doors":4},
        {"model":"Escort", "doors":4}
    ]
}
}

I would like to add a new cars brand (in addition to Nissan and Ford), using circe at scala.
How could I do it?

Thank you in advance.

1 Answer 1

3

You can modify JSON using cursors. One of the possible solutions:

import io.circe._, io.circe.parser._

val cars: String = """
{
  "cars": {
    "Nissan": [
      {"model":"Sentra", "doors":4},
        {"model":"Maxima", "doors":4},
        {"model":"Skyline", "doors":2}
     ],
    "Ford": [
      {"model":"Taurus", "doors":4},
      {"model":"Escort", "doors":4}
    ]
  }
}"""

val carsJson = parse(cars).getOrElse(Json.Null)
val teslaJson: Json = parse("""
    {
      "Tesla": [
        {"model":"Model X", "doors":5}
      ]
    }""").getOrElse(Json.Null)

val carsCursor = carsJson.hcursor
val newJson = carsCursor.downField("cars").withFocus(_.deepMerge(teslaJson)).top

Here we just go down to cars field, "focus" on it and pass the function for modifying JSON values. Here deepMerge is used.

newJson will be look as follows:

Some({
  "cars" : {
    "Tesla" : [
      {
        "model" : "Model X",
        "doors" : 5
      }
    ],
    "Nissan" : [
      {
        "model" : "Sentra",
        "doors" : 4
      },
      {
        "model" : "Maxima",
        "doors" : 4
      },
      {
        "model" : "Skyline",
        "doors" : 2
      }
    ],
    "Ford" : [
      {
        "model" : "Taurus",
        "doors" : 4
      },
      {
        "model" : "Escort",
        "doors" : 4
      }
    ]
  }
})
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, that's it. Thank you!

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.