Convert scala list to Json object

I want to convert a scala string list, List [String], to a Json object.

For every line in my list, I want to add it to my Json object.

To make it look something like this:

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

How to create a json object like this from my list of strings?

+4
source share
2 answers

To directly answer your question, a very simplistic and hacker way to do this:

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

However, what you almost certainly want to do is select one of the many JSON libraries: play-json gets good comments, as does lift-json . In the worst case scenario, you can just get a simple JSON library for Java and use it.

+10
source

Since I am familiar with lift-json, I will show you how to do this with this 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 expression names -> List(...) implicitly converted by JsonDSL, since I indicated that I wanted it to lead to a JObject , so now json is the json data model you wanted.

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

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

Be sure to check out the documentation where you are likely to find answers to any additional questions about json elevator support.

+3
source

All Articles