Search code examples
scalajson4s

How to convert json to string with escape characters using json4s


I am trying to create a JSON which will have strings as values. One of the element will have JSON in String format as values

Eg:

input: {"foo":"bar","nestedFoo":[{"foo":"bar"}]}

output: {"foo" : "bar", "nested_foo_as_string":"[{\"foo\":\"bar\"}]"}

I could do String replaceAll to replace quotes with escaped quotes. But, just wanted to post this question to know if there is there a straightforward way to get the JSON to string with escape characters using json4s.?

I know there is a way to do it in python with json.dumps(json.dumps()) , but could not find a cleaner way to do it using json4s.

Appreciate any inputs.


Solution

  • Something like this should work... if you're purely transforming json, I think going to and from case classes is a bit of a distraction:

    val input = """{"foo" : "bar", "nestedFoo":[{"foo":"bar"}]}"""
    val transformed = parse(input).transformField {
      case ("nestedFoo", x) => ("nested_foo_as_string", JString(compact(render(x))))
    }
    val output = compact(render(transformed))