How to load JSON file using Play with Scala
From Play 2.6, Environment has the getExistingFile
, getFile
, resource
and resourceAsStream
methods, E.g.:
class Something @Inject (environment: play.api.Environment) {
// ...
environment.resourceAsStream("data.json") map ( Json.parse(_) )
(Note, in this case data.json is inside the conf folder)
https://www.playframework.com/documentation/2.6.x/api/scala/index.html#play.api.Environment
Looks like the comment about the possible duplicate is how to read a file from your app/assets folder. My answer is about how to parse Json from a stream. Combine the two and you should be good to go.
Json.parse
accepts a few different argument types, one of which is InputStream
.
val stream = new FileInputStream(file)
val json = try { Json.parse(stream) } finally { stream.close() }
P.S. When you can't find what you're looking for in the written docs, the API Docs are a good place to start.
Here is how I managed to solve it:
val source: String = Source.fromFile("app/assets/jsons/countriesToCities.json").getLines.mkString
val json: JsValue = Json.parse(source)
Thanks for the help! :)