Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert scala list to Json object

Tags:

json

list

scala

I want to convert a scala list of strings, List[String], to an Json object.

For each string in my list I want to add it to my Json object.

So that it would look like something like this:

{
 "names":[
  {
    "Bob",
    "Andrea",
    "Mike",
    "Lisa"
  }
 ]
}

How do I create an json object looking like this, from my list of strings?

like image 696
malmling Avatar asked Mar 19 '13 10:03

malmling


2 Answers

To directly answer your question, a very simplistic and hacky way to do it:

val start = """"{"names":[{"""
val end = """}]}"""
val json = mylist.mkString(start, ",", end)

However, what you almost certainly want to do is pick one of the many JSON libraries out there: play-json gets some good comments, as does lift-json. At the worst, you could just grab a simple JSON library for Java and use that.

like image 76
Impredicative Avatar answered Nov 06 '22 15:11

Impredicative


Since I'm familiar with lift-json, I'll show you how to do it with that library.

import net.liftweb.json.JsonDSL._
import net.liftweb.json.JsonAST._
import net.liftweb.json.Printer._
import net.liftweb.json.JObject

val json: JObject = "names" -> List("Bob", "Andrea", "Mike", "Lisa")

println(json)
println(pretty(render(json)))

The names -> List(...) expression is implicitly converted by the JsonDSL, since I specified that I wanted it to result in a JObject, so now json is the in-memory model of the json data you wanted.

pretty comes from the Printer object, and render comes from the JsonAST object. Combined, they create a String representation of your data, which looks like

{
  "names":["Bob","Andrea","Mike","Lisa"]
}

Be sure to check out the lift documentation, where you'll likely find answers to any further questions about lift's json support.

like image 4
Dylan Avatar answered Nov 06 '22 15:11

Dylan