• Selenium Video Tutorials

Selenium Webdriver - JSON Data File



Selenium Webdriver can be used to interact with the json data file. Often in an automation test, there remains a need to feed a large amount of data through a json file for a test case to verify a specific scenario or to create a data driven framework. A json file contains data in key-value pairs and it has an extension of .json.

Java provides few classes and methods to carry out read and write data operations on a json file using the JSON Simple libraries. The JSON Simple is library of lightweight nature used to manipulate JSON objects

How to Install the JSON Simple?

Step 1 − Add the JSON Simple dependencies from the below link −

https://mvnrepository.com/artifact/.

Step 2 − Save the pom.xml with all the dependencies and update the maven project.

Example 1 - Read all Values From a Json File

Let us take an example of the below json named the Detail.json file, where we will read the whole json file and retrieve all its values using the JSONParser class and its method parse().

Seleniu JSON File 1

The contents of the Detail.json file is −

{
   "name": "Ram",
   "email": "abc@gmail.com",
   "home": [
      {
         "road": "TUY",
         "zip": "700008"
      },
      {
         "road": "TUX",
         "zip": "700061"
      }
   ]
}

Once we retrieve the values from the Detail.json file, we would input the values of the name, and email keys in the below page within the Full Name, and Email fields.

Seleniu JSON File 2

Please Note: The Details.json file was placed within the project under the Resources folder as shown in the below image.

Seleniu JSON File 3

Code Implementation on JSONRead.java class file.

package org.example;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class JSONRead {
   public static void main(String[] args) throws IOException, ParseException {

      //object of JSONParser
      JSONParser j = new JSONParser();

      // load json file to be read
      FileReader f = new FileReader("./Resources/Detail.json");

      // parse json content
      Object o = j.parse(f);

      // convert parsing object to JSON object
      JSONObject detail = (JSONObject)o;

      // get values from JSON file
      String name = (String)detail.get("name");
      String email = (String)detail.get("email");
      System.out.println("First Name: " + name);
      System.out.println("Email: " + email);

      // get values from JSON array
      JSONArray h = (JSONArray)detail.get("home");

      // iterate through the JSONArray
      for(int i = 0; i < h.size(); i ++){
         JSONObject home = (JSONObject) h.get(i);
         String road = (String)home.get("road");
         String zip = (String)home.get("zip");
         System.out.println("Road: " + road);
         System.out.println("Zip: " + zip);
      }
      
      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 12 secs
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);

      // Opening the webpage
      driver.get("https://www.tutorialspoint.com/selenium/practice/text-box.php");

      //Identify elements
      WebElement n = driver.findElement(By.xpath("//*[@id='fullname']"));
      WebElement m = driver.findElement(By.xpath("//*[@id='email']"));

      // enter name and email after reading from JSON file
      n.sendKeys(name);
      m.sendKeys(email);

      // get values entered
      String enteredName = n.getAttribute("value");
      String enteredEmail = m.getAttribute("value");
      System.out.println("Entered Name: " + enteredName);
      System.out.println("Entered Email: " + enteredEmail);

      // quitting browser
      driver.quit();
   }
}

Dependencies added to pom.xml.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>
   
   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>
      
      <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
      <dependency>
         <groupId>com.googlecode.json-simple</groupId>
         <artifactId>json-simple</artifactId>
         <version>1.1.1</version>
      </dependency>
   </dependencies>
</project>

Output

First Name: Ram
Email: abc@gmail.com
Road: TUY
Zip: 700008
Road: TUX
Zip: 700061
Entered Name: Ram
Entered Email: abc@gmail.com

Process finished with exit code 0

In the above example, we had read the whole json file and obtained all its value in the console with message - First Name: Ram, Email: abc@gmail.com, Road: TUY, Zip: 700008, Road: TUX, and Zip: 700061.Then entered the values of First Name, and Email obtained by reading the JSON file to the input boxes on the web page, and also retrieved the value entered with the messages in the console - Entered Name: Ram, and Entered Email: abc@gmail.com.

Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.

Example 2 - Write and Read Values in a Json File

Let us take another example where we will create a json file named Detail1.json under the Resources folder in the project and write some values in it.

package org.example;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class JSONReadWrite {
   public static void main(String[] args) throws IOException, ParseException {

      // object of JSONObject
      JSONObject j = new JSONObject();

      // generate key-value pairs in JSON file
      j.put("Name", "Selenium");
      j.put("Language", "Java");

      // create JSON file with no duplicate values
      FileWriter f = new FileWriter("./Resources/Detail1.json", false);

      // write on json file
      f.write(j.toJSONString());

      // close file after write
      f.close();

      //object of JSONParser
      JSONParser j1 = new JSONParser();

      // load json file to be read
      FileReader f1 = new FileReader("./Resources/Detail1.json");

      // parse json content
      Object o = j1.parse(f1);

      // convert parsing object to JSON object
      JSONObject detail = (JSONObject)o;

      // get values from JSON file
      String name = (String)detail.get("Name");
      String language = (String)detail.get("Language");
      System.out.println("Name: " + name);
      System.out.println("Language: " + language);
   }
}

Dependencies added to pom.xml.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>
   
   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>
      
      <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
      <dependency>
         <groupId>com.googlecode.json-simple</groupId>
         <artifactId>json-simple</artifactId>
         <version>1.1.1</version>
      </dependency>
   </dependencies>
</project>

Output

Name: Selenium
Language: Java

Process finished with exit code 0

In the above example, we created a json file Detail1.json under the Resources folder inside the project and wrote some values in it. Then we read all those values, and finally obtained them in the console with messages -Name: Selenium, and Language: Java.

Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.

Also, the json with the filename Detail1.csv got created in the project directory. On clicking it, we would get the values written through the above code.

Seleniu JSON File 4

This concludes our comprehensive take on the tutorial on Selenium Webdriver - JSON Data File. We’ve started with describing what is a JSON Simple library, how to install JSON Simple, and walked through examples of how to read and write values in json taking help of JSON Simple along with Selenium Webdriver. This equips you with in-depth knowledge of the JSON Data File in Selenium Webdriver. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.

Advertisements