6

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?

0

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.