duckertito duckertito - 2 days ago 5
Scala Question

Cut off the field from JSON string

I have a JSON string like this:

{"id":"111","name":"abc","ids":["740"],"data":"abc"}


I want to cut off the field
"ids"
, however I don't know apriori the values like
["740"]
. So, it might be e.g.
["888,222"]
or whatever. The goal is to get the json string without the field
"ids"
.

How to do it? Should I use
JackMapper
?

EDIT:

I tried to use
JackMapper
as
JacksMapper.readValue[Map[String, String]]
(jsonString)
to get only fields that I need. But the problem is that
"ids":["740"]` throws the parsing error because it's an array. So, I decided to cut off this field before parsing, though it's an ugly solution and ideally I just want to parse the json string into Map.

Answer

Not sure what JackMapper is, but if other libraries are allowed, my personal favourites would be:

Play-JSON:

val jsonString = """{"id":"111","name":"abc","ids":["740"],"data":"abc"}"""
val json = Json.parse(jsonString).as[JsObject]
val newJson = json - "ids"

Circe:

import io.circe.parser._

val jsonString = """{"id":"111","name":"abc","ids":["740"],"data":"abc"}"""
val json = parse(jsonString).right.get.asObject.get // not handling errors
val newJson = json.remove("ids")

Note that this is the minimal example to get you going which doesn't handle bad input etc.

Comments