score:18
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! :)
score:0
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] =
Option(Source.fromFile(filename).mkString)
.map(Json.parse)
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)
score:6
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
score:26
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.
Source: stackoverflow.com
Related Query
- How to load JSON file using Play with Scala
- How to send email with attached file in scala and play framework (2.3.9) using activator?
- How to respond with a pretty-printed JSON object using play framework?
- How can I deserialize from JSON with Scala using *non-case* classes?
- How to fetch records from the database using Play with Scala and Slick
- How to convert a json with a single value to a case class using play json
- How to create nested json using Apache Spark with Scala
- How to update a nested json using scala play framework?
- How to update each field in a list using Play json in Scala
- How to read json array in scala using the Play framework
- How do parse fixed-position file with multiple sections in Spark using Scala
- How to read a JSON file into a Map, using Scala
- How to map multiple Futures and pass them as arguments to a view using Play with Scala
- How do I serialize CharSequence to JSON with Play 2.1 and Scala
- How to load xml file in scala with databinding enabled
- how to create connection pool in scala using mysql with play 2.2
- How to get rid of extra escape characters while doing json transformation using scala play framework?
- How to save output of multiple queries under single JSON file in appended mode using spark scala
- Scala : Read JSON file with Play
- How to load a json file which is having double quotes within a string into a dataframe in spark scala
- how to convert properties file to JSON using scala
- How to create a Scala executable jar file that is built with Maven, and has log4j included, using IntelliJ IDEA IDE
- How to populate drop down box from conf file using Scala / Play Framework
- How to replace value in json using scala play json
- How to use a JSON mapping file to generate a new DataFrame in Spark using Scala
- How to convert json file to List using scala
- Using java classes in Play framework with Scala to be returned as Json Object
- How to serialize a java.util.Map[String, Object] to JSON in Scala using Play 2.3.9?
- Using Play framework with Scala, how can I humanize a Json Validation message?
- How to convert list data into Json in scala using play framework?
More Query from same tag
- How to subscribe to remote events in Akka
- Scala type constraint of companion type
- Update and select in single query . Sql syntax error in Scala
- Convert tuple to a List of first item
- Pattern matching..error says Error:(11, 11) type mismatch; found : Unit
- How do I convert a Java byte array into a Scala byte array?
- How to know if a Scala file modified with IntelliJ Idea is saved and if it is checked into CVS?
- How to fix "error: not found: type CosmosDBSourceProvider" in databricks scala read stream from cosmos db
- Concurrency, how to create an efficient actor setup?
- What is the equivalent of "@SpringBootApplication(exclude={SecurityAutoConfiguration.class})" in scala?
- Initialize several objects at once
- Why does Array.fill take an implicit scala.reflect.ClassManifest?
- Spark - adding multiple columns under the same when condition
- Provide implicit evidence for a type alias in Scala
- cors in akka http with headerValueByName issue (akka-http-cors)
- Why am i getting this "HttpRequestAction - 'httpRequest-1' failed to execute: No attribute named"
- mavericks intellij scala not configuring properly
- Scala: find diffs in lists with different structure
- Improve scala list query
- UnsupportedClassVersionError on play with JDK 1.7
- error: overloaded method value options with alternatives
- How to create a sequence of timestamps in Scala
- SBT console doesn't want to launch in intelliJ
- How to use flatMapValues on Kafka
- SparkSession throw Could not find or load main class
- Unable to override a method from child class in scala
- Scala, how to set up a node class?
- Scala, check if Actor has exited
- How to count occurrences of a word inside a Array in scala when using spark?
- Omitting dots when chaining calls