Read JSON File in Scala

“JavaScript Object Notation, or JSON, is a coding language. The greatest replacement for XML is a completely separate data interchange format. The process of parsing a JSON file and obtaining the essential data from it is covered in this guide. JSON is a simple data exchange format that is simple for robots to parse and generate data from, as well as for humans to read and write. It is a specific text format that is not language-specific. There are several libraries available that can parse JSON, making it challenging to choose the best one for our Scala services. Circe, Circe Optics, and lift-JSON, which we found to be the greatest choice because of how well it handles JSON.”

Example # 1: Parsing JSON With Circe in Scala in Ubuntu 20.04

The Circe Scala package makes working with JSON easier by making it simple to decode JSON strings into Scala objects or convert Scala objects to JSON. We need fewer lines of code to interact with JSON in Scala and thanks to the library’s automatic generation of object encoders and decoders.

In this instance, we have imported the circe package and the deriveDecoder, which enables us to parse a JSON string depending on the “Animal” case class. The case class represents the object “readJson,” and the object is called the main definition. We have defined the variable “json_value,” which is initialized with the JSON format data. The implicit decoder function, deriveDecoder, from Circe’s case class is what we need to provide in this example. The error will occur if we don’t offer the implicit. Under the hood, the implementation of the parser.decode called the “Animal” class and assigned parameter “json_value” to it. Then, we have a matched identifier that will return one of two cases.

We have decoded the JSON data into the scala by using the circe scala package as follows:

Example # 2: Parsing JSON Array in Scala in Ubuntu 20.04

An array can be used to start JSON. So let’s use Circe to try and parse that.

It resembles the earlier code in appearance. First, we have imported two circe packages. Then, we have defined the case class “Fruits,” and it contains one parameter, “f_name”. We have established the “ReadArray” for the main method definition. Then, we declare the variable “inputJson” to represent the JSON data. However, you might have noticed a few things. Only the case class Fruits decoder needs to be created. List[Fruits] does not require a decoder to be created. This is so that Circe can conveniently decode List[A].

A generic type is indicated by the inList[A] of any kind. Circe does encode and decodes each type separately. The “Result” variable matches the case, which will return either the Right case on the success of parsing JSON to Scala or the Left case on failure.

Example # 3: Parsing JSON String in Scala in Ubuntu 20.04

The Circe-Core package contains the Cursor object, available in three different forms: Cursor, HCursor, and ACursor. With this, data may be extracted from or modified within the JSON structure. We will decode in the following example using an algebraic data type. You may compare it to enumeration if you are unfamiliar with it.

With importing the scala circe packages, we have begun code implementation. We have defined three case classes, “football”, “hockey”, and “tennis,” which are extended with the object “Level”. Also, we have generated the case class “Error” for exception handling. Then, we have represented the object “Level”. We have utilized the “Either” keyword, which takes the Level and error inside it. The “Either” has two children, right and left, which are called with the case statement. The right case will be executed on success, and the left case will execute on failure.

We have established another object as a “Decoder” for the primary code implementation. Here, we have created a variable “Json” and assigned the JSON data, which contains three strings. The implicit variable is defined as “ratingDecoder” which is called the “Decoder” object and passes the Either[Error, Level] to it. We have invoked the cursor object “Hcursor” which will modify the JSON structure. Under the implementation of the parse function, we have parsed the JSON data. The JSON will be parsed and generated into scala when matched with the specified case statements.

You can see that Decoder[Either[Error, Level]] appears to satisfy all the requirements. The code above, when executed, yields the expected outcomes.

Example # 4: Parsing JSON With Lift-JSON Library in Scala in Ubuntu 20.04

Use a combination of the Lift-JSON library’s techniques. The example that follows demonstrates how to deserialize the string jsonString into many objects while displaying each object as it is deserialized as follows:

After that, we defined a class “EmployeesAccount”. The case class contains some attributes with the specified data types. Then, we created the “ParseJsonArray” and defined a string called jsonString that contains some sample JSON data. After that, we declared the variable “json” where we invoked the parse function. The parse function converts this string into a JValue object with the name json.

The \\ method is then used to search the json data for every element with the name “email”. This syntax is good since it matches the XPath-like techniques employed in the Scala XML library. The for loop repeatedly searches for items, extracts each element as an “Email” object, then prints the contents of that object’s data. We have passed some of the fields to the println statement that will only be parsed into the scala.

The following Scala output is obtained after running the program to parse JSON data.


Two approaches were presented in this article: one used circe Scala methods, and the other used a well-known Lift-JSON to parse the JSON text. The Circe Scala utility facilitates interaction with JSON through the use of an easy-to-use API. We can always create a custom encoder or decoder, or we may use the field extraction code directly to change the behavior of the system. And we realized that, because of their features and ease of development, Both are always favored when parsing.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.