Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load JSON file using Play with Scala

Tags:

I need to load a JSON file with a list of cities in one of my controllers, in order to pass it to a view afterwards.

I have placed the file here: app/assets/jsons/countriesToCities.json
(By the way: is this an appropriate location, or should I place it somewhere else?)

I have read the docs and I can see it is possible to create a JsValue from a string: https://www.playframework.com/documentation/2.4.x/ScalaJson#Using-string-parsing

I want to create a JsValue in a similar fashion. The difference is that I want to load the content from a file, not from a string... I haven't found any code snippet on how to do this, unfortunately.
Do I have to use something else to read the file into a string and only then use the parse method on that string?

Code snippets with examples on how to do this in the answers will be highly appreciated! :)

Thank you very much in advance!

like image 640
Henrique Ferrolho Avatar asked Dec 17 '15 12:12

Henrique Ferrolho


People also ask

What is the best json library for Scala?

Argonaut is a great library. It's by far the best JSON library for Scala, and the best JSON library on the JVM. If you're doing anything with JSON in Scala, you should be using Argonaut.

What is play JSON?

The Play JSON library. The play. api. libs. json package contains data structures for representing JSON data and utilities for converting between these data structures and other data representations.


1 Answers

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.

like image 64
Dylan Avatar answered Oct 17 '22 12:10

Dylan