Skip to content

Instantly share code, notes, and snippets.

@marcusdb
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save marcusdb/41e496fde52b245c9a61 to your computer and use it in GitHub Desktop.

Select an option

Save marcusdb/41e496fde52b245c9a61 to your computer and use it in GitHub Desktop.
JSON to SQL
package models
import scala.collection.JavaConversions.asScalaIterator
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
object Processor {
val mapper: ObjectMapper = new ObjectMapper();
def parseSql(str: String) = {
def processOper(node: JsonNode) = {
node.path("oper").asText() match {
case "eq" => "="
case "lteq" => ">="
case "lt" => ">"
case "steq" => "<="
case "st" => "<"
}
}
def process(node: JsonNode): String = {
val currentNode = node
currentNode.path("type").asText() match {
case "and" =>
" (" + currentNode.path("list").elements().map(element => process(element)).mkString(" AND ") + ") "
case "or" =>
" (" + currentNode.path("list").elements().map(element => process(element)).mkString(" OR ") + ") "
case "text" =>
currentNode.path("field").asText() + "='" + currentNode.path("value").asText + "'"
case "number" =>
currentNode.path("field").asText() + processOper(currentNode) + currentNode.path("value").asDouble
case "date" =>
currentNode.path("field").asText() + processOper(currentNode) + " FROM_UNIXTIME(" + currentNode.path("value").asLong + ")"
}
}
process(mapper.readTree(str))
}
}
object App {
def main(args: Array[String]) {
val str = """
{"type":"and","list":[
{"type":"text","field":"alou","value":"val"},
{"type":"number","field":"alou","value":10,"oper":"eq"},
{"type":"date","field":"alou","value":223423840238,"oper":"eq"},
{"type":"or","list":[
{"type":"text","field":"alou","value":"val"},
{"type":"text","field":"alou","value":"val"},
{"type":"number","field":"alou","value":10,"oper":"eq"},
{"type":"date","field":"alou","value":223423840238,"oper":"eq"},
{"type":"or","list":[{"type":"text","field":"alou","value":"val"},{"type":"text","field":"alou","value":"val"}]}
]}
]}
"""
println(Processor.parseSql(str))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment