简体   繁体   English

如何使用json4s将json转换为带有转义字符的字符串

[英]How to convert json to string with escape characters using json4s

I am trying to create a JSON which will have strings as values. 我正在尝试创建一个将字符串作为值的JSON。 One of the element will have JSON in String format as values 元素之一将具有String格式的JSON作为值

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. 我可以用String replaceAll来用转义的引号替换引号。 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.? 但是,只是想发布这个问题,以了解是否存在使用json4s将JSON转换为带有转义字符的JSON的简单方法。

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. 我知道有一种方法可以在python中使用json.dumps(json.dumps()),但是找不到使用json4s的更干净的方法。

Appreciate any inputs. 感谢任何输入。

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: 像这样的事情应该起作用...如果您纯粹是在转换json,我认为进出案例类会让人分心:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM