Search code examples
jsonscalalift-json

Lift JSON: How to convert convert list of tuples to JsonAST?


The following code produces a List[JsonAst.JObject]:

val json = recommendations.map { r =>
  ("cardId" -> r._1) ~
  ("count" -> r._2)
}

This one doesn't. It produces List[(String, Int)]:

val json = recommendations.map { r =>
  (r._1.toString -> r._2)
}

How can I convert this List[(Int, Int)] into JSON?


Solution

  • For org.json4s.json library

    Since (r._1.toString -> r._2) doesn't produce a JObject without the ~ operator, you need to lift it manually to JObject, which takes a list of Tuples as Parameter:

    val json = recs.map { r =>
      JObject(List(JField(r._1, JInt(r._2))))
    }
    

    Produces:

    List[JsonAST.JObject]
    

    EDIT for net.liftweb.json library

    val json = recs.map { r =>
      JObject(List(JField(r._1, JInt(r._2))))
    }
    

    EDIT Both libraries allow the same syntax