JSON Question

Translating JSON values using io.circe

I have a function in scala that translates a value and produces a string.

strOut = translate(strIn)


Suppose the following JSON object:

{
"id": "c730433b-082c-4984-3d56-855c243265f0",
"standard": "stda",
"timestamp": "tsx000",
"stdparms" : {
"stdparam1": "a",
"stdparam2": "b"
}
}


and the following mapping provided by the translation function:

"stda" -> "stdb"
"tsx000" -> "tsy000"
"a" -> "f"
"b" -> "g"


What is the best way to translate the whole JSON object using the translate function? My goal is to obtain the following result:

{
"id": "c730433b-082c-4984-3d56-855c243265f0",
"standard": "stdb",
"timestamp": "tsy000",
"stdparms" : {
"stdparam1": "f",
"stdparam2": "g"
}
}


I must use the
io.circe
library due to project related matters.

Answer Source

If you know beforehand which fields you want to translate, or what translations apply to that field, you can use Cursors to traverse the JSON tree. Or if the fields themselves are fixed (you always know what fields to expect) Optics may require less code.

When you get to the right leaf, you apply the translation.

However, when you don't know what could apply when/where it might be easier to find/replace using string methods.

Note that the JSON you provided as an example is not valid JSON by the way.