Accepted answer

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! :)


I usually need few small dictionaries to live in memory in order to build some plain LUTs (LookUp Tables). In order to achieve that I use the following piece of code (please it is worth noting I am using latest Play 2.6):

def loadJSONFromFilename(filename: String): Option[JsValue] =

Using the previous function is just a matter of passing a filename path. Tailoring this to be used with Play you might need to place your file in a resource folder and to enable it you need to place this in your build.sbt file:

// include resources into the unversal zipped package using sbt dist
mappings in Universal ++= directory(baseDirectory.value / "resources")

Thus, you can use this resource folder this way in your Play class:

lazy val lutFilePath: Path = 
  Paths.get(env.rootPath.getAbsolutePath, "resources", "lut.json")
lazy val lutJson = loadJSONFromFilename(lutFilePath.toString)


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)


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.

Related Query

More Query from same tag