user1756420
user1756420

Reputation: 49

Scala: Convert Json JObject to List

I have this sample URL: https://api.github.com/repos/jdan/isomer/languages The difference in output here is that its not normally how we expect JSON to be i.e. "label": "value". It is "Language_Name":"Number of lines".

When i call this api from my scala code:

val responseLangUrl: HttpResponse[String] = Http(url").asString
val responseLangUrlJson = parse(responseLangUrl.body)
println(responseLangUrlJson)

Output is:

JObject(List((Ruby,JInt(2622))))
JObject(List((CoffeeScript,JInt(3513)), (JavaScript,JInt(380))))

JInt is insignificant to me. I want list of all these language names. How can i extract that?

https://github.com/json4s/json4s: This official link has example for "label":"value"case but how i extract something like this i.e. type of JSON where i directly have information.

Upvotes: 1

Views: 4687

Answers (2)

Angelo Genovese
Angelo Genovese

Reputation: 3398

import org.json4s._
import org.json4s.jackson.JsonMethods._

implicit val formats = DefaultFormats

parse("""
 {
   "JavaScript": 54179,
   "CSS": 508,
   "HTML": 406
}
""").foldField(List(): List[String])((l, t) => t._1 :: l)

results in

res0: List[String] = List(HTML, CSS, JavaScript)

Upvotes: 3

mohit
mohit

Reputation: 4999

The simplest way IMO, is to convert JSON into Map[String, Any] and then extract the keys.

parse("""
 {
   "JavaScript": 54179,
   "CSS": 508,
   "HTML": 406
}
""").extract[Map[String, Any]].map(_._1)
res0: scala.collection.immutable.Iterable[String] = List(JavaScript, CSS, HTML)

Upvotes: 1

Related Questions