Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

Modifying a JSON array in Scala with circe

I have a JSON string with array as the following:

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

I would like to edit a new card brand, using circe at scala.
Instead of

"Nissan": [
        {"model":"Sentra", "doors":4},
        {"model":"Maxima", "doors":4},
    ]

I would like to have as a result:

"Nissan": [
        {"model":"Sentra", "doors":1000},
    ],

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Made after reading the manual, please do the same next time!

Apart from your JSON being invalid (Trailing comma on object in array "Nissan"), it should look something like this:

import cats.syntax.either._
import io.circe._, io.circe.parser._

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

val newJson = parse(json).toOption
  .flatMap { doc =>
    doc.hcursor
      .downField("cars")
      .downField("Nissan")
      .withFocus(_ =>
          Json.arr(
            Json.fromFields(
              Seq(
                ("model", Json.fromString("Sentra")),
                ("doors", Json.fromInt(1000))
              )
            )
          )
      )
      .top
  }

newJson match {
  case Some(v) => println(v.toString)
  case None => println("Failure!")
}

Try it out! (Rerun to see correct indentation!)


newJson is actually an Option, so if parsing or modifying fails, you will get None.

Calling toOption on parse(json) converts the returned Either[Json] (parsing succeeded / failed) to an Option[Json].

We need to use an Option[Json] in the first place because .top returns a Option[Json] (modifying succeeded / failed), too.

This way we can flatMap and don't have to deal with any nested types (see here).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...