How to Use JsonUtils to Read Test Data from JSON Files in automationframeworkselenium

JsonUtils is a static utility class that provides both simple key-value lookups via get() and powerful JSONPath queries via getData() to extract configuration and test data from JSON files without writing custom parsing logic.

The JsonUtils class located in src/main/java/com/anhtester/utils/JsonUtils.java serves as the central JSON handler for the automationframeworkselenium test automation framework. It combines the Jackson library for flat configuration maps with the JsonPath library for complex nested queries, enabling testers to access test data using either simple string keys or expressive path expressions.

JsonUtils Architecture and Data Loading Patterns

Static Configuration Map for Global Settings

On class loading, JsonUtils initializes a static HashMap<String, String> called CONFIGMAP that stores framework-wide configuration values. The static initialization block reads the file specified by FrameworkConstants.JSON_DATA_FILE_PATH using Jackson's ObjectMapper.

// From JsonUtils.java lines 44-46
static {
    CONFIGMAP = new ObjectMapper()
        .readValue(new File(SystemHelpers.getCurrentDir() 
            + FrameworkConstants.JSON_DATA_FILE_PATH),
        new TypeReference<HashMap<String, String>>() {});
}

The constant FrameworkConstants.JSON_DATA_FILE_PATH resolves to the property value JSON_DATA_FILE_PATH defined in your properties files via PropertiesHelpers.getValue(), creating a configurable entry point for the primary JSON data file.

Dynamic JSONPath Context for Test Data

For complex test data structures, JsonUtils maintains a DocumentContext object from the JsonPath library. The setJsonFile(String jsonPath) method reads any specified JSON file into a StringBuffer and parses it into a queryable context.

// From JsonUtils.java lines 80-88
bufferedReader = new BufferedReader(new FileReader(
    SystemHelpers.getCurrentDir() + jsonPath));
// ... accumulate into stringBuffer ...
jsonContext = JsonPath.parse(stringBuffer.toString());

If no file is explicitly set, the getData() method automatically loads a default store.json located at src/test/resources/datajson/store.json as the data source.

Practical Usage Patterns

Retrieving Simple Configuration Values

Use the get(String key) method to fetch flat key-value pairs from the static config map. This approach ignores case sensitivity and is ideal for global settings like URLs, browser types, or environment flags.

import com.anhtester.utils.JsonUtils;

public class ConfigExample {
    public void setupTest() {
        String baseUrl = JsonUtils.get("url");           // e.g., "https://myapp.com"
        String browser = JsonUtils.get("BROWSER");       // e.g., "chrome"
        String timeout = JsonUtils.get("TIMEOUT");       // case-insensitive lookup
    }
}

Querying Nested Data with JSONPath

For hierarchical test data, use getData(String jsonPathExpression) to evaluate JSONPath expressions against the loaded context. This method supports array indexing, recursive descent, and filter expressions.

// Using the default store.json
JsonUtils.getData("$.store.book[0]");                    // First book object
JsonUtils.getData("$.store.book[0].category");          // Specific field
JsonUtils.getData("$.store.bicycle");                    // Nested object

// Switching to a custom file
JsonUtils.setJsonFile("src/test/resources/datajson/tools.json");
JsonUtils.getData("$.tool.jsonpath.creator.name");      // Deep nested value

Working with Multiple JSON Files

When tests require data from different JSON sources, explicitly switch files using setJsonFile(). The method accepts a relative path from the project root, automatically resolving the full path via SystemHelpers.getCurrentDir().

@Test
public void testProductCatalog() {
    // Load product data
    JsonUtils.setJsonFile("src/test/resources/datajson/products.json");
    String productName = JsonUtils.getData("$.products[0].name");
    
    // Switch to user data for the same test
    JsonUtils.setJsonFile("src/test/resources/datajson/users.json");
    String userEmail = JsonUtils.getData("$.users[?(@.id==1)].email");
}

Complete Implementation Example

The following TestNG test class demonstrates both configuration lookups and JSONPath queries in practice, mirroring the implementation in TestSimpleCode.java.

import com.anhtester.utils.JsonUtils;
import com.anhtester.helpers.JsonHelpers;
import org.testng.annotations.Test;

public class JsonDataTest {

    @Test
    public void readConfigValues() {
        // Static config map lookups
        System.out.println(JsonUtils.get("url"));
        System.out.println(JsonUtils.get("BROWSER"));
    }

    @Test
    public void readFromDefaultStore() {
        // Default store.json queries
        System.out.println(JsonUtils.getData("$.store.book[0]"));
        System.out.println(JsonUtils.getData("$.store.book[0].category"));
    }

    @Test
    public void readFromCustomFile() {
        // Explicit file loading with JSONPath
        JsonUtils.setJsonFile("src/test/resources/datajson/tools.json");
        System.out.println(JsonUtils.getData("$.tool.jsonpath.creator.name"));
        System.out.println(JsonUtils.getData("$.tool.jsonpath.creator.email"));
    }

    @Test
    public void readWithJsonHelpers() {
        // Alternative helper class instance
        JsonHelpers helper = new JsonHelpers();
        helper.setJsonFile("src/test/resources/datajson/book.json");
        System.out.println(helper.getData("$.book[1].title"));
        System.out.println(helper.getData("$.['price range'].cheap"));
    }
}

Summary

  • JsonUtils centralizes JSON handling in src/main/java/com/anhtester/utils/JsonUtils.java using Jackson for flat maps and JsonPath for complex queries.
  • Static initialization loads the config file defined by FrameworkConstants.JSON_DATA_FILE_PATH into a case-insensitive CONFIGMAP accessible via get().
  • Dynamic queries use setJsonFile() to load arbitrary JSON files and getData() to evaluate JSONPath expressions, defaulting to src/test/resources/datajson/store.json.
  • Path resolution relies on SystemHelpers.getCurrentDir() to ensure files are loaded relative to the project root across different execution environments.

Frequently Asked Questions

What is the default JSON file path used by JsonUtils?

If setJsonFile() is never called, the getData() method automatically loads store.json from src/test/resources/datajson/store.json. This fallback is defined in the jsonFilePathDefault field and loaded via the getJsonDataSourceString() method when the jsonContext is null.

How does JsonUtils handle case sensitivity for configuration keys?

The get(String key) method performs case-insensitive lookups against the static CONFIGMAP. This means JsonUtils.get("browser"), JsonUtils.get("BROWSER"), and JsonUtils.get("Browser") all return the same value from the configuration JSON.

Can I use JsonUtils to parse JSON arrays and nested objects?

Yes. While the static get() method only supports flat key-value strings, the getData(String jsonPathExpression) method uses the JsonPath library to extract values from any depth, including array indices ($.store.book[0]), recursive descent ($..author), and filter expressions ($.book[?(@.price<10)]).

What is the difference between JsonUtils and JsonHelpers?

JsonUtils is a static utility class designed for framework-wide use with a shared state (single jsonContext), while JsonHelpers is an instance-based helper class located in src/main/java/com/anhtester/helpers/JsonHelpers.java that mirrors the same API for parallel test execution scenarios. JsonHelpers allows multiple tests to maintain separate JSON contexts simultaneously without interfering with each other.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →