top of page
back.jpg

Retrieve data from a JSON file

Updated: Feb 10

To retrieve data from a JSON file using Java and Selenium, you can use a library like Gson or Jackson for handling JSON parsing.


{
  "username": "Tester1",
  "password": "Test1234",
}

package com.seleniumExamples2024;

import java.io.FileReader;
import java.io.Reader;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class RetrievDataFromJson {
	public static void main(String[] args) {
		try {
 // Specify the path to your JSON file
            String jsonFilePath = ".//Userdata.json";
 // Create a FileReader to read the JSON file
            Reader reader = new FileReader(jsonFilePath);
  // Use Gson to parse the JSON content
            Gson gson = new Gson();
 JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
    // Retrieve data from the JsonObject
            String username = jsonObject.get("username").getAsString();
            String password = jsonObject.get("password").getAsString();
            String url = jsonObject.get("url").getAsString();
   // Print the retrieved data
            System.out.println("Username: " + username);
            System.out.println("Password: " + password);
            System.out.println("URL: " + url);
    // Close the reader
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

Use Python

import json

# Specify the path to your JSON file
json_file_path = "./Tester.json"

# Read the JSON file
with open(json_file_path, 'r') as file:
    # Load the JSON content
    data = json.load(file)

# Access and print specific values from the loaded data
print("Name:", data["name"])
print("Age:", data["age"])
print("City:", data["city"])
print("Is Student:", data["isStudent"])
print("Skills:", data["skills"])


JSON file Example

{
 "employees": {
  "employee": [{
  "name": "John Doe",
  "age": 20,
  "city": "New York",
  "isStudent": true,
  "skills": ["Java", "C#", "Python", "JavaScript"]
},
{
  "name": "John Smith",
  "age": 30,
  "city": "Raleigh",
  "isStudent": false,
  "skills": ["Java", "Python", "JavaScript", "Ruby"]
},
{
  "name": "Kattie josh",
  "age": 23,
  "city": "Ellicott city",
  "isStudent": true,
  "skills": ["Java", "Python", "JavaScript"]
}
 ]
 }
}
package com.seleniumExamples2024;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class EmployeeDataFromJson2 {

	public static void main(String[] args) {

		try {
    // Specify the path to your JSON file
			String jsonFilePath = "Employees.json";

	// Read the JSON file as a string
			String jsonContent = new String(Files.readAllBytes(Paths.get(jsonFilePath)));

    // Parse the JSON content using Jackson
	ObjectMapper objectMapper = new ObjectMapper();
	JsonNode rootNode = objectMapper.readTree(jsonContent);

    // Retrieve the "employees" JSON array
			JsonNode employeesArray = rootNode.get("employees").get("employee");

   // Iterate over each employee object
			for (JsonNode employee : employeesArray) {
				String name = employee.get("name").asText();
				int age = employee.get("age").asInt();
				String city = employee.get("city").asText();
				boolean isStudent = employee.get("isStudent").asBoolean();
				JsonNode skillsArray = employee.get("skills");

	// Print employee information
				System.out.println("\nName: " + name);
				System.out.println("Age: " + age);
				System.out.println("City: " + city);
				System.out.println("Is Student: " + isStudent);
				System.out.print("Skills: ");
				for (JsonNode skill : skillsArray) {
					System.out.print(skill.asText());
		if (skill != skillsArray.get(skillsArray.size() - 1)) {
						System.out.print(", ");
					}
				}
				System.out.println();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

5 views0 comments

Recent Posts

See All

Test case for Valid Coupon Code

This test case checks whether a valid coupon code is successfully applied to a booking cart, the total is updated accordingly, and a success message is displayed. package com.seleniumExamples2024; pu

Keyboard shortcut keys for various operations

General Shortcuts: Ctrl + C: Copy Ctrl + X: Cut Ctrl + V: Paste Ctrl + Z: Undo Ctrl + Y: Redo Ctrl + A: Select All Ctrl + S: Save Ctrl + P: Print Ctrl + F: Find Windows Shortcuts: Windows Key: Open or

Comentários

Avaliado com 0 de 5 estrelas.
Ainda sem avaliações

Adicione uma avaliação
bottom of page