Open In App

How to read and write JSON files in Scala?

Last Updated : 27 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Scala is frequently used for reading and writing JSON files in a variety of applications, particularly it includes data transmission.

Steps for reading JSON files in Scala:

When reading JSON files in Scala we follow these steps:

  • Opening the file for reading using Scala's Source.fromFile method. We can read data from the file using the Source object that is returned by this method.

val source = Source.fromFile(filePath);

  • We can read data from the Source object Using the mkString method we can read the entire file into a single string.

val content = source.mkString;

  • Once the JSON content is read we need to parse it into scala data structures like string, list, etc.
  • It is important to handle the errors while performing operations with files.

Steps for writing JSON files in Scala:

When writing JSON files in Scala we follow these steps :

  • Firstly, we need to create JSON content that we need to write into a file. That can be represented in the form of a map, list, etc.,

val file = new File(filePath);

  • For opening the file for writing we use File, PrintWriter classes.
  • Create a new PrintWriter instance with the file path as an argument.

val writer = new PrintWriter(file);

  • To write the single line or multiple lines JSON content into the file we use the write method from the PrintWriter instance.

writer.write(jsontext);

  • After completion of writing JSON content into the file, we need to close the PrintWriter to release system resources.

writer.close();

  • It is important to handle the errors while performing operations with files.

Example:

Let's try to write JSON data into a file and read JSON data from the file using Scala.

import scala.io.Source;
import scala.util.{Try, Success, Failure};
import java.io.{File, PrintWriter};

object Main {
  def main(args: Array[String]): Unit = {
    val filePath = "json_file.json";
    val jsontext ="""{"Name": "Jimin", "Age": 26, "Company": "Hybe", "City" : "Seoul"}""";
    writeToJsonFile(filePath, jsontext) match {
      case Success(_) => println(s"JSON data is written into file: $filePath");
      case Failure(exception) => println(s"Failed to write JSON into a json file: ${exception.getMessage}");
    };
    val jsontext1 = readFromJsonFile(filePath);
    jsontext1 match {
      case Success(content) => println("Content present in json file:\n" + content);
      case Failure(exception) => println(s"Failed to read JSON data from file: ${exception.getMessage}");
    };
  };
  
  def writeToJsonFile(filePath: String, jsontext: String): Try[Unit] = {
    Try {
      val file = new File(filePath);
      val writer = new PrintWriter(file);
      writer.write(jsontext);
      writer.close();
    };
  };
  
  def readFromJsonFile(filePath: String): Try[String] = {
    Try {
      val source = Source.fromFile(filePath);
      val content = source.mkString;
      source.close();
      content;
    };
  };
};

Output
JSON data is written into file: json_file.json
Content present in json file:
{"Name": "Jimin", "Age": 26, "Company": "Hybe", "City" : "Seoul"}

Explanation:

  • First we have imported the classes that are required for writing, reading of data and for handling of errors.
  • Main method defines the file path where the JSON data is read and write from. It also contains the data to be written into the file, error handling cases, and we call for the functions for reading and writing.
  • If the respective files doesn't exist then it raises an exception. writeToJsonFile function takes the filepath and data that needs to be written into the file.
  • PrintWriter instance writes the data into the file and then closes it. readToJsonFile takes the file path, using Source.fromFile it opens the file and reads the data using mkString, closes it and then returns the string.

Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg