user9920500
user9920500

Reputation: 705

How to convert a sequence of Tuples into JSON array in spray

I have an array of student IDs which is dynamic in scala.

val studentIds = Seq(1,2,3,4....)

I should convert them into a JSON array in Spray JSON.

like

[
 {"student_id" : 1 },
 {"student_id" : 2 },
 {"student_id" : 3 },
]

How to do it without a case class?

Upvotes: 1

Views: 743

Answers (2)

sachin teotia
sachin teotia

Reputation: 141

You can use the below code snippet-

import spray.json.{JsNumber, JsObject}
val studentIds = Seq(1,2,3,4).map{x => JsObject("student_id" -> JsNumber(x))}
  
println(studentIds)

Upvotes: 0

jgoday
jgoday

Reputation: 2836

You can use Maps. Each map will be translated directly to an json object.

import spray.json._
import DefaultJsonProtocol._

val studentIds = Seq(1,2,3,4).map(s => Map("student_id" -> s))

println(studentIds.toJson)

Upvotes: 3

Related Questions