Convert scala list to Json object

16,698

Solution 1

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.

Solution 2

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.

Share:
16,698
malmling
Author by

malmling

Updated on June 30, 2022

Comments

  • malmling
    malmling almost 2 years

    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?

  • Srinivasu
    Srinivasu over 2 years
    val start = """"{"names":[{"""" val end = """"}]}""" val json = mylist.mkString(start, """","""", end)