0

Is there an easy way to convert List[String] to String format with " and ,. For example

val fruits: List[String] = List("Apple", "Banana", "Grapes", "Pears")
==> "Apple", "Banana", "Grapes", "Pears"

I want to do this because I have to append the result in JSON string.

{
 ....,
 "fruits": ["Apple", "Banana", "Grapes", "Pears"],
 ....
}
1
  • 4
    s""""${fruits.makeString(", ")}"""" But what if some of the values contain double quotes? Crafting json "by hand" is actually, suprisingly harder than it looks. So, better, do something standard, like Jackson.mapper.writeValueAsString(fruits). Commented Jan 10, 2017 at 0:14

1 Answer 1

6
fruits.mkString("\"fruits\": [\"", "\",\"", "\"]")

but I'd use something like https://github.com/circe/circe instead of building JSONs myself

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

3 Comments

It fails if strings in fruits have quotes.
As dima mentioned in the comments - it is hard to wrangle your own JSON. That's why I suggested using a library that does that for you like Circe
I will be glad to remove my comment as soon as the answer will describe the reason for using libraries. From my point of view the answer has to warn users about possible problems too.

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.