简体   繁体   English

在scala中格式化JSON字符串

[英]Format JSON string in scala

Is there a straight forward way to format a JSON string in scala? 是否有直接的方式在Scala中格式化JSON字符串?

I have a JSON String like this: 我有一个像这样的JSON字符串:

val json = {"foo": {"bar": {"baz": T}}}

Can I use a function f such that: 我可以使用以下函数f

f(json) = {
           "foo": 
                {"bar": 
                       {"baz": T}
                }
           }

I know the formatting I have done in my answer is no perfect, but you get the point. 我知道我在回答中所做的格式化并不完美,但是您明白了。 And yes, can it be done without using Play Framework? 是的,不使用Play框架就可以做到吗?

In case you are using Play Framework you could use Json.prettyPrint method to format JsValue : 如果您使用的是Play Framework ,则可以使用Json.prettyPrint方法设置JsValue格式:

import play.api.libs.json.Json

val str = """{"foo": {"bar": {"baz": "T"}}}"""

val jsValue = Json parse str
// JsValue = {"foo":{"bar":{"baz":"T"}}}

Json prettyPrint jsValue
// String = 
// {
//   "foo" : {
//     "bar" : {
//       "baz" : "T"
//     }
//   }
// }

In case you are using scala.util.parsing.json you have to create such method by yourself. 如果您使用的是scala.util.parsing.json ,则必须自己创建此类方法。 For instance: 例如:

def format(t: Any, i: Int = 0): String = t match {
  case o: JSONObject =>
    o.obj.map{ case (k, v) =>
      "  "*(i+1) + JSONFormat.defaultFormatter(k) + ": " + format(v, i+1)
    }.mkString("{\n", ",\n", "\n" + "  "*i + "}")

  case a: JSONArray =>
    a.list.map{
      e => "  "*(i+1) + format(e, i+1)
    }.mkString("[\n", ",\n", "\n" + "  "*i + "]")

  case _ => JSONFormat defaultFormatter t
}

val jsn = JSON.parseRaw("""{"foo": {"bar": {"baz": "T"}, "arr": [1, 2, "x"]}, "foo2": "a"}""").get
// JSONType = {"foo" : {"bar" : {"baz" : "T"}, "arr" : [1.0, 2.0, "x"]}, "foo2" : "a"}

format(jsn)
// String = 
// {
//   "foo": {
//     "bar": {
//       "baz": "T"
//     },
//     "arr": [
//       1.0,
//       2.0,
//       "x"
//     ]
//   },
//   "foo2": "a"
// }

Note that this is not an efficient implementation. 请注意,这不是有效的实现。

I thought I read somewhere that Typesafe was considering separating their JSON processing out of Play, so look into that to apply @senia's solution first. 我以为我读过某个地方,Typesafe正在考虑将其JSON处理从Play中分离出来,因此请研究一下以首先应用@senia的解决方案。

Otherwise, look at Jackson--or more precisely, the Scala wrapper for Jackson : 否则,请看一下Jackson,或更准确地说,看一下Jackson的Scala包装器

val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
val writer = mapper.writerWithDefaultPrettyPrinter
val json = writer.writeValueAsString(Object value)

I've also heard that the kids are really into Scala Pickling , which apparently has pretty printing as well. 我还听说孩子们真的很喜欢Scala酸洗 ,它的印刷工艺也很漂亮。

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

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