在scala中使用递归函数解析复杂地图
Posted
技术标签:
【中文标题】在scala中使用递归函数解析复杂地图【英文标题】:Parsing a complex map using recursive function in scala 【发布时间】:2019-11-23 10:42:04 【问题描述】:我有一个像下面这样的 json 文件
"Item Version": 1.0,
"Action2": "true12",
"Item Creation Time": "2019-04-14 14:15:09",
"Trade Dictionary":
"Country": "India",
"TradeNumber": "1",
"action":
"Action2": true,
"Action1": false
,
"Value": "XXXXXXXXXXXXXXX"
,
"Payments":
"abc": "def",
"Payment Details": [
"Payment Date": "2019-04-11",
"Payment Type": [
"Payval": "myval "
]
]
我有一个这样的 scala 代码
def secondFlatten(map: Map[String, Any]):Map[String, Any]=val c=map.flatten
val c=map.flatten
case ((key, map : Map[String, Any])) =>
map.flatten
case ((innerKey: String, l: List[Map[String, Any]])) => l.head.flatten
case ((key1: String, l1: List[Map[String, Any]]))=>l1.head.mapcase (x:String, y: Any)=> (s"$key->$innerKey->$key1->$x"-> y)
case ((key1: String, m1 : Map[String, Any])) => m1.mapcase (x:String, y: Any)=> (s"$key->$innerKey->$key1->$x"-> y)
case (key1: String, value1: String) => Map(s"$key->$innerKey->$key1"-> value1)
case ((innerKey: String, m : Map[String, Any])) => m.mapcase (x:String, y: Any)=> (s"$key->$innerKey->$x"-> y)
case (innerKey: String, value: String) => Map(s"$key->$innerKey"-> value)
case ((key, value)) => Map(key -> value)
.toMap
return c
返回这样的值
(付款->付款明细->付款日期,2019-04-11)
(贸易字典->价值,XXXXXXXXXXXXXXX)
(付款->付款明细->付款类型->Payval,myval)
(贸易词典->国家,印度)
(贸易字典->贸易编号,1)
(交易字典->action->Action1,false)
(Action2,true12)
(项目版本,1.0)
(交易字典->action->Action2,true)
(物品创建时间,2019-04-14 14:15:09)
(付款->abc,def)
有没有办法写一个递归函数而不是放同一种case语句???
【问题讨论】:
【参考方案1】:给你:
def flattenMap(m: Map[String, Any], tree: List[String] = List()) : Iterable[(String, Any)] = m.flatten
case (k: String, v: Map[String, Any] @unchecked) => flattenMap(v, tree :+ k)
case (k: String, v: List[Map[String, Any]] @unchecked) => v.flatten(flattenMap(_, tree :+ k))
case (k: String, v: Any) => List((tree :+ k.toString).mkString("->") -> v)
case (k: String, null) => List((tree :+ k).mkString("->") -> null)
(此处回复:https://scastie.scala-lang.org/benrobby/9fWtDyvyTt28BEul6UJ4Bg)
【讨论】:
如果 value 为 null 或任何数字,这将不起作用..就像键值对是 "CLS": true, "money":2.378 "userComments": null,对于这种情况,我们得到匹配错误 只需添加另一个案例陈述,更新我的答案。以上是关于在scala中使用递归函数解析复杂地图的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Scala 中使用 Stream.cons 编写不泄漏的尾递归函数?