使用json4s从json字符串中提取键

时间:2022-03-09 21:15:20

can someone tell me how to extract keys from json using json4s. My use case: json stored as string in scala variable:

谁能告诉我如何使用json4s从json中提取密钥。我的用例:json存储为scala变量中的字符串:

 {
 "key1" : "val1",
 "key2" : ["12", "32"],
 "key3" : {"keyN" : "valN"}
 }

I'd like to transform this into a following Map[String, String]:

我想将其转换为以下Map [String,String]:

 (key1 -> "val1", key2 -> "[\"12\",\"32\"]", key3 -> "{\"keyN\":\"valN\"}"

is there a simple way to achieve this with json4s? Thanks in advance

有没有一种简单的方法来实现这个与json4s?提前致谢

2 个解决方案

#1


4  

val result: Map[String, String] = parse( """ {
                                           | "key1" : "val1",
                                           | "key2" : ["12", "32"],
                                           | "key3" : {"keyN" : "valN"}
                                           | }""".stripMargin).mapField(k => {
  val v: String = k._2 match {
    case s: JString => k._2.extract[String]
    case _ => write(k._2)
  }
  (k._1, JString(v))
}).extract[Map[String, String]]
println(result)

You can use mapField map the JValue toString

您可以使用mapField映射JValue toString

  • if the value's type is String just extract as String
  • 如果值的类型是String,则只提取为String
  • if the value's type is others, use the json4s to parse it to as JSON string
  • 如果值的类型是其他类型,请使用json4s将其解析为JSON字符串
  • finally extract the JValue as Map[String, String].
  • 最后将JValue提取为Map [String,String]。

#2


0  

implicit val formats = DefaultFormats

val a = parse(""" { "numbers" : [1, 2, 3, 4] } """)
println(a.extract[Map[String, Any]].keySet)

#1


4  

val result: Map[String, String] = parse( """ {
                                           | "key1" : "val1",
                                           | "key2" : ["12", "32"],
                                           | "key3" : {"keyN" : "valN"}
                                           | }""".stripMargin).mapField(k => {
  val v: String = k._2 match {
    case s: JString => k._2.extract[String]
    case _ => write(k._2)
  }
  (k._1, JString(v))
}).extract[Map[String, String]]
println(result)

You can use mapField map the JValue toString

您可以使用mapField映射JValue toString

  • if the value's type is String just extract as String
  • 如果值的类型是String,则只提取为String
  • if the value's type is others, use the json4s to parse it to as JSON string
  • 如果值的类型是其他类型,请使用json4s将其解析为JSON字符串
  • finally extract the JValue as Map[String, String].
  • 最后将JValue提取为Map [String,String]。

#2


0  

implicit val formats = DefaultFormats

val a = parse(""" { "numbers" : [1, 2, 3, 4] } """)
println(a.extract[Map[String, Any]].keySet)