0

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?

Wonko
  • 176
  • 1
  • 9

1 Answers1

1

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

thwiegan
  • 2,163
  • 10
  • 18
  • I get a type mismatch `found : (Int, net.liftweb.json.JsonAST.JInt)` but `required: net.liftweb.json.JsonAST.JField` – Wonko Aug 04 '15 at 20:38
  • Okay apparently we use different libraries. My imports are: `import org.json4s._ import org.json4s.JsonDSL._` These were included in my dev stack. Will check for yours. – thwiegan Aug 04 '15 at 20:54
  • @Wonko Edited accordingly – thwiegan Aug 04 '15 at 21:05
  • Had to use .toString for name parameter: `JObject(List(JField(r._1.toString, JInt(r._2))))` – Wonko Aug 04 '15 at 21:31
  • @Wonko So you had an Integer in the first field of the tuple? Sorry didn't catch that from your question. But yes if you want a number as key, you need to .toString it. If it helped, please mark as accepted answer. – thwiegan Aug 04 '15 at 21:34