JSON file

JSON is an open-standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs.

In fact, JSON is an acronym and translated into JavaScript Object Notation. Its inventor is famously quoted for having said “It doesn’t take a rocket scientist to create a better (relational) file format for JavaScript than XML.

Which implies its purposes. He’s right (Douglas Crockford), unfortunately it (also) doesn’t take a rocket scientist to create a better (relational) file format than JSON too. I should now, because I’ve arguably done the latter myself.


									 #JSON file
									{
										"cat": {
											"legs": 4,
											"colour": "brown"
										}
									}			
									

JSON main usage is for transmitting data, often from a server to a client, to facilitate for AJAX. AJAX is what facilitates for a rich experience on the web, allowing for incrementally apply changes to a website, using data from the server.

The format is widely accepted everywhere as it is lightweight alternative of XML, XML is difficult to read, JSON much easier. Also JSON takes less storage compared to XML.

JSON Parser is inbuilt in most browsers, and JSON is also a widely accepted data exchange format against XML web services for the same.

Due to its ease of use and the relative popularity of JavaScript frameworks json is being used in rest APIs and whenever the JavaScript code in the browser communicates with the server.

JSON allows multiple systems and languages to communicate in an agreed way, much like an international language.

Reading a JSON File in Protractor

Copy the below content into a file and save the file with .json format, For example : cherchertech.json


									#cherchertech.json  file
									{ 
										"name": "karthiq",
										"age": 27,
										"gender": "Male",
										"website": "cherchertech protractor"
									}			
									

To read the JSON data from the file, we can use the fs module present in the Node.js. fs module manipulates the files present in the system like read, write and update.

There are two functions available in this module that we can use to read files from the file system:

  • readFileSync
  • readFile

Read file using readFileSync :

The readFileSync function reads data from a file in a synchronous manner. readFileSync function blocks the rest of the code from executing until all the data is read from a file.

The function is particularly useful when your application has to load configuration settings before it can perform any other tasks.

Below code will help you to read the total json file, and also print it to console.


// import the fs module
const fs = require('fs');
// read the file into raw data
let rawdata = fs.readFileSync('cherchertech.json');  
// parse the raw data into meaningful JSON format
let author = JSON.parse(rawdata);  
console.log(author);  			


read-json-file-protractor

Read a Value from JSON file with Protractor:

In above code, we have read the total Json file and printed it to the console, but when it come to real life, we would not just stop with reading the file, we have to use the individual value for some purpose.

Let's say use the above code snippet into out protractor program and search in google using the "website" value present in the json file.

  • As usual, crate a describe and it blocks using Jasmine and protractor
  • 
    								describe('Protractor Typescript Demo', function() {
    									browser.ignoreSynchronization = true; // for non-angular websites
    									it('Javascript executions', function() {
    								

  • import the fs modules using require
  • 
    								// import the fs module
    								const fs = require('fs');	
    								

  • Call readFileSync method and pass the file path as a parameter and store return value of the readFileSync method
  • 
    								// read the file into raw data
    								let rawdata = fs.readFileSync('D:\\Protractor Demo\\cherchertech.json');
    								

  • Now parse the stored value into JsonObject using JSON.parse() method and pass the stored object as parameter.
  • JSON.parse parses the raw data into a string map
  • 
    								// parse the raw data into meaningful JSON format
    								let web = JSON.parse(rawdata); 	
    								

  • Read the string map and retrieve the values using key web["website"]
  • 
    								let websiteValue = web["website"]		
    								

  • Open the Google and find the search bar using name attribute q and set the value using sendKeys method

Read a value from a Json file using Protractor


								import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
								import { Alert, WebElement } from 'selenium-webdriver';

								describe('Protractor Typescript Demo', function() {
									browser.ignoreSynchronization = true; // for non-angular websites
									it('Json File Reading', function() {
										// set implicit time to 30 seconds
										browser.manage().timeouts().implicitlyWait(30000);
										// navigate to the url
										browser.get("http://google.com");
										// import the fs module
										const fs = require('fs');
										// read the file into raw data
										let rawdata = fs.readFileSync('D:\\Protractor Demo\\cherchertech.json');  
										// parse the raw data into meaningful JSON format
										let web = JSON.parse(rawdata); 
										let websiteValue = web["website"]
										console.log("Website value from Json file is : " +websiteValue) 
										element(by.name("q")).sendKeys(websiteValue);
									});
								});			
								


json-file-read-protractor

Read Json file value using readFile with Protractor:

Another way you can read a JSON file in Node.js is using the readFile function. Unlike readFileSync function, the readFile function reads file data in an asynchronous manner.

When a readFile function is called, the file reading process starts and immediately the control shifts to next line executing the remaining lines of code.

Once the file data has been loaded, this function will call the callback function provided to it. This way you aren't blocking code execution while waiting for the operating system to get back to you with data.

Below example showcases, how to use the readFile() method in protractor.


import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
import { Alert, WebElement } from 'selenium-webdriver';

describe('Protractor Typescript Demo', function() {
	browser.ignoreSynchronization = true; // for non-angular websites
	it('Javascript executions', function() {
		// set implicit time to 30 seconds
		browser.manage().timeouts().implicitlyWait(30000);
		// navigate to the url
		browser.get("http://google.com");
		// import the fs module
		const fs = require('fs');
		// read the file into raw data
		let rawdata = fs.readFile("D:\\Protractor Demo\\cherchertech.json", 'utf8', function(err, contents) {
			// parse the raw data into meaningful JSON format
			let web = JSON.parse(contents); 
			let websiteValue = web["website"]
			console.log("Website value from Json file is : " +websiteValue)
			// see below for the note
			browser.sleep(5000) 
			element(by.name("q")).sendKeys(websiteValue);
		});  	
	});
});			
In above code i have used sleep(), because rawdata() method gets executed before even trying to execute any other command in the code.

As I explained earlier, rawdata() method is asynchronous, so it will always tries to execute as early as possible. Due to this reason I have added a sleep so please, do choose method to read the data from Json file in protractor care fully

Read Json File using require in protractor

Normally we use require for importing the node modules, and packages but we can use it for loading the Json file in protractor.

with this method, we donot have to use wait statement and it is not an asynchronous method to read. I prefer this method for reading Json file along with protractor.


									import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
									import { Alert, WebElement } from 'selenium-webdriver';

									describe('Protractor Typescript Demo', function() {
										browser.ignoreSynchronization = true; // for non-angular websites
										it('Javascript executions', function() {
											// set implicit time to 30 seconds
											browser.manage().timeouts().implicitlyWait(30000);
											// navigate to the url
											browser.get("http://google.com");
											// load the Json file
											const totalContent = require('D:\\Protractor Demo\\cherchertech.json');

											let websiteValue = totalContent["website"]
											console.log("Website value from Json file is : " +websiteValue)
											element(by.name("q")).sendKeys(websiteValue);
										});
									});			
									


Rules for using require along with Json in protractor:

  • Require is synchronous function and is called only once, which means the calls receive a cached result.
  • If the file is updated, you can't re-read it using this method
  • Your file must have '.json' extension, so it can't be as flexible. Without the proper extension require doesn't treat the file as JSON file.

Read Nested JSON File as test data in protractor

The actual truth is you may not be working with simple json files like above, most of the time Json files will have nested values like below file.

We may save our test data in JSON files in protractor, As JSOn files are platform independent so JSON files are good option fot sroring test data in protractor.

Save the content of below in some file with JSON extension.


{ 
"author":{
    "name": "karthiq",
    "age": 27,
    "gender": "Male",
    "website": {
        "name": "chercher tech",
        "tagline": "Learning is Fun",
        "topics": "Future technologies"
        }
    }
}			


From above files lets read the "tagline" value present inside "website" value, the website values are present inside "author value.

For reading nested values we may need to group the values similar to a map, In below example we will be searching the "tagline" value in google.

  • Create a describe and it blocs for in Jasmine
  • Import the fs module (you can directly import json file)
  • 
    const fs = require('fs');		
    
  • Call readFileSync() from the fs module in javascript
  • 
    // read the file into raw data
    let rawdata = fs.readFileSync('D:\\Protractor Demo\\cherchertech.json');				
    
  • Let's try to fetch the total json file value and print it
  • Filter "author" value from the total values of the json file.
  • 
    let author = web["author"]
    browser.sleep(1).then(function(){
    	console.log("\n\n###### Author value ########\n")
    	console.log(author)
    })			
    
  • Again filter the website value from the author values
  • 
    let website = author["website"]
    browser.sleep(1).then(function(){
    	console.log("\n\n****** Website value ******\n")
    	console.log(website)
    })			
    
  • Filter the "tagline" value from the website value
  • 
    let taglineBySteps = website["tagline"]
    browser.sleep(1).then(function(){
    	console.log("\n\n@@@@@@ tagline value @@@@@\n")
    	console.log(taglineBySteps)
    })			
    
  • Filtering means nothing but adding [key] to the value we have
  • Instead of step by step filtering. you directly get the values for a specific key
  • 
    let taglineDirect = web["author"]["website"]["tagline"]
    browser.sleep(1).then(function(){
    	console.log("\n\n^^^^^^^ tagline value  Direct^^^^^^\n")
    	console.log(taglineDirect)
    })			
    
  • Search in google for that tagline value using protractor
Complete program for reading nested JSON file in Protractor with Typescript

import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
import { Alert, WebElement } from 'selenium-webdriver';

describe('Protractor Typescript Demo', function() {
	const fs = require('fs');
	let sampleMap = new Map();
	browser.ignoreSynchronization = true; // for non-angular websites
	it('Javascript executions', function() {
		// set implicit time to 30 seconds
		browser.manage().timeouts().implicitlyWait(30000);
		// navigate to the url
		browser.get("http://google.com");
		
		const fs = require('fs');
		// read the file into raw data
		let rawdata = fs.readFileSync('D:\\Protractor Demo\\cherchertech.json');
		
		// parse the raw data into meaningful JSON format
		let web = JSON.parse(rawdata);
		
		let author = web["author"]
		browser.sleep(1).then(function(){
			console.log("\n\n###### Author value ########\n")
			console.log(author)
		})
		
		let website = author["website"]
		browser.sleep(1).then(function(){
			console.log("\n\n****** Website value ******\n")
			console.log(website)
		})
		
		let taglineBySteps = website["tagline"]
		browser.sleep(1).then(function(){
			console.log("\n\n@@@@@@ tagline value @@@@@\n")
			console.log(taglineBySteps)
		})
		
		let taglineDirect = web["author"]["website"]["tagline"]
		browser.sleep(1).then(function(){
			console.log("\n\n^^^^^^^ tagline value  Direct^^^^^^\n")
			console.log(taglineDirect)
		})
		element(by.name("q")).sendKeys(taglineBySteps);
	});
});		


Output of the reading nested JSON values program


[11:13:05] I/local - Selenium standalone server started at http://172.19.113.1:54633/wd/hub
Started


###### Author value ########

{ name: 'karthiq',
  age: 27,
  gender: 'Male',
  website: 
   { name: 'chercher tech',
     tagline: 'Learning is Fun',
     topics: 'Future technologies' } }


****** Website value ******

{ name: 'chercher tech',
  tagline: 'Learning is Fun',
  topics: 'Future technologies' }


@@@@@@ tagline value @@@@@

Learning is Fun


^^^^^^^ tagline value  Direct^^^^^^

Learning is Fun
.

1 spec, 0 failures
Finished in 2.695 seconds			


nested-json-values-typescript-protractor

Check whether Webpage loaded or not in Javascript in Protractor

Create a Json File in Protractor

Sometimes we may need to write the files as well, similar to the readFile and readFileSync functions, there are two functions for writing data to files:

  • writeFileSync
  • writeFile

The writeFile method writes data to a file in an asynchronous way while writeFileSync function writes data to a file in a synchronous manner.


										const fs = require('fs');
										let site = {  
											name: 'cherchertech',
											previousName: "selenium-webdriver.com"
										};
										let data = JSON.stringify(site);  
										fs.writeFileSync('site-details.json', data);			
										


write-json-files-protractor

Write values to Json File in protractor :

In above topic, we have seen how to write predefined values into protractor but when it comes to the protractor we may need to fetch values from the web page and store it into Json file.

In below example, We will be fetching the title and font-size attribute from the google search bar into Json file.

I would recommend to read how to get font-size(css value) and title attribute in protractor


											import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
											import { Alert, WebElement } from 'selenium-webdriver';

											describe('Protractor Typescript Demo', function() {
												const fs = require('fs');
												browser.ignoreSynchronization = true; // for non-angular websites
												it('Javascript executions', function() {
													// set implicit time to 30 seconds
													browser.manage().timeouts().implicitlyWait(30000);
													// navigate to the url
													browser.get("http://google.com");
													// get attribute
													element(by.name("q")).getAttribute("title").then(function(toolTip){
														// get css value
														element(by.name("q")).getCssValue("font-size").then(function(font_size){
															let googleBar = {  
																title: toolTip,
																fontSize: font_size
															};
															let data = JSON.stringify(googleBar);  
															fs.writeFileSync('searchbarDetails.json', data);
														})
													})
												});
											});			
											


write-json-file-css-value-attribute-protractor In above output, you can see that the json file is store in a single line, but it is not so readable to make it more readable pass few more parameters with JSON.stringfy method


										let data = JSON.stringify(sampleMap, null, 3); 			
										

Here the parameter 3 is nothing but how many spaces we have to give for each row, I have used this in below, converting Typescript Map to Json file with protractor program.

Create Select class for handling dropdowns in protractor

Convert Typescript Map into Json file along with Protractor

Most of the time we will store a collection of objects either in List or in Map, we can convert this map into JSON file format, but we cannot convert list into json file format because Map stores the values in key-Value pair format similar to Json files.


import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
import { Alert, WebElement } from 'selenium-webdriver';

describe('Protractor Typescript Demo', function() {
	const fs = require('fs');
	let sampleMap = new Map();
	browser.ignoreSynchronization = true; // for non-angular websites
	it('Javascript executions', function() {
		// set implicit time to 30 seconds
		browser.manage().timeouts().implicitlyWait(30000);
		// navigate to the url
		browser.get("http://google.com");
		
		// get attribute
		element(by.name("q")).getAttribute("title").then(function(toolTip){
			// get css value
			element(by.name("q")).getCssValue("font-size").then(function(font_size){
				sampleMap["title"] = toolTip;
				sampleMap["fontSize"] = font_size;
				let data = JSON.stringify(sampleMap, null, 3); 
				fs.writeFileSync('abc.json', data);
			})
		})
	});
});			


map-to-json-protractor

Protractor Interview Questions

 
Join My Facebook Group
Join Group
 

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • Mahendar
    Hi KarthiQ,
    
    Could you please send me the offline protractor notes.
    
    Thanks in advance,
    Mahendar
    Reply
  • Copyright © CherCher Tech