json4s icon indicating copy to clipboard operation
json4s copied to clipboard

#suggestion/#request: snippet in README.md for flatten function from Extract

Open alexDeCastroAtGit opened this issue 8 years ago • 1 comments

json4s version

latest

scala version

11.7

jdk version

0.8

Hi there, would it be possible to include a little snippet on Extract.flatten on the project page? Or the Extract package as a whole. I ended-up writing my own flatterer to find out later, through the following link

https://searchcode.com/codesearch/view/69075744/

that json4s had already a tail-recursive flattening function... -_-*

I can compare the results now with your version.

I'm mentioning that for the benefit of the community as a whole. A lot of people in parsing and processing data benefit from flat Json.

Anyway, food for thought. Love you guys project, Alex

alexDeCastroAtGit avatar Apr 06 '17 14:04 alexDeCastroAtGit

P.S.: the flattener assuming the I have the values of a serialized json.

def flatten(t: List[(String, Any)]): List[(String, Any)] = t match {
  case Nil => Nil

  case (s, m) :: xs if m.isInstanceOf[Map[String, Any]] => {
    val m_new = concatenateKeys(s, m.asInstanceOf[Map[String, Any]]) // update names
    flatten(m_new.toList) ::: flatten(xs)
  }
    // special case
  case (s, ms) :: xs if ms.isInstanceOf[List[Any]] => {
    val out = ms.asInstanceOf[List[Any]].map{m => {
      if (m.isInstanceOf[List[String]]) m.asInstanceOf[List[String]]
        .map{r => (r, "")}
        .map{case (k, v) => (s + "." + k, v)}
      else
      if (m.isInstanceOf[Map[String, Any]]) {
        val m_new = concatenateKeys(s, m.asInstanceOf[Map[String, Any]]) // update names
        flatten(m_new.toList)
      }
      else List((s, ms)) // fix this: **BUG** // there's room for improvement here
    }}.asInstanceOf[List[List[(String, Any)]]].flatten ::: flatten(xs)
    out
  }
  case x :: xs => x :: flatten(xs)
}

alexDeCastroAtGit avatar Apr 06 '17 14:04 alexDeCastroAtGit