CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-jayway-jsonpath--json-path

A Java DSL for reading JSON documents using JsonPath expressions, similar to XPath for XML

Pending
Overview
Eval results
Files

document-context.mddocs/

Document Context Operations

Comprehensive read and write operations on parsed JSON documents. DocumentContext provides both reading capabilities and document modification features, combining ReadContext and WriteContext interfaces.

Capabilities

Document Parsing

Factory methods for creating DocumentContext instances from various JSON sources.

/**
 * Parses JSON object using default configuration
 * @param json Parsed JSON object (Map, List, etc.)
 * @return DocumentContext for path operations
 */
public static DocumentContext parse(Object json);

/**
 * Parses JSON string using default configuration
 * @param json JSON string to parse
 * @return DocumentContext for path operations
 */
public static DocumentContext parse(String json);

/**
 * Parses JSON file using default configuration
 * @param json File containing JSON data
 * @return DocumentContext for path operations
 * @throws IOException If file cannot be read
 */
public static DocumentContext parse(File json) throws IOException;

/**
 * Parses JSON input stream using default configuration
 * @param json Input stream containing JSON data
 * @return DocumentContext for path operations
 */
public static DocumentContext parse(InputStream json);

/**
 * Parses JSON with specific configuration
 * @param json JSON source (Object, String, File, or InputStream)
 * @param configuration Configuration to use for parsing
 * @return DocumentContext for path operations
 */
public static DocumentContext parse(Object json, Configuration configuration);
public static DocumentContext parse(String json, Configuration configuration);
public static DocumentContext parse(File json, Configuration configuration) throws IOException;
public static DocumentContext parse(InputStream json, Configuration configuration);

Usage Examples:

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Option;

String json = "{ \"users\": [{ \"name\": \"Alice\", \"age\": 30 }] }";

// Parse with default configuration
DocumentContext context = JsonPath.parse(json);

// Parse with custom configuration
Configuration config = Configuration.builder()
    .options(Option.SUPPRESS_EXCEPTIONS)
    .build();
DocumentContext configuredContext = JsonPath.parse(json, config);

// Parse from file
DocumentContext fileContext = JsonPath.parse(new File("data.json"));

Reading Operations

Reading data from the parsed JSON document using path expressions.

/**
 * Returns the configuration used for reading
 * @return Immutable configuration
 */
public Configuration configuration();

/**
 * Returns the JSON model this context operates on
 * @return JSON model as object
 */
public <T> T json();

/**
 * Returns the JSON model as a JSON string
 * @return JSON model as string
 */
public String jsonString();

/**
 * Reads the given path from this context
 * @param path JsonPath expression
 * @param filters Optional predicates for filtering
 * @return Result matching the path
 */
public <T> T read(String path, Predicate... filters);

/**
 * Reads the given path with type mapping
 * @param path JsonPath expression
 * @param type Expected return type
 * @param filters Optional predicates for filtering
 * @return Result mapped to specified type
 */
public <T> T read(String path, Class<T> type, Predicate... filters);

/**
 * Reads using a compiled JsonPath
 * @param path Compiled JsonPath instance
 * @return Result matching the path
 */
public <T> T read(JsonPath path);

/**
 * Reads using a compiled JsonPath with type mapping
 * @param path Compiled JsonPath instance
 * @param type Expected return type
 * @return Result mapped to specified type
 */
public <T> T read(JsonPath path, Class<T> type);

/**
 * Reads using a compiled JsonPath with generic type reference
 * @param path Compiled JsonPath instance
 * @param typeRef Type reference for generic types
 * @return Result mapped to specified generic type
 */
public <T> T read(JsonPath path, TypeRef<T> typeRef);

/**
 * Reads with generic type reference
 * @param path JsonPath expression
 * @param typeRef Type reference for generic types
 * @return Result mapped to specified generic type
 */
public <T> T read(String path, TypeRef<T> typeRef);

Usage Examples:

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.TypeRef;
import java.util.List;
import java.util.Map;

DocumentContext context = JsonPath.parse(json);

// Basic reading
String name = context.read("$.users[0].name");
List<String> allNames = context.read("$.users[*].name");

// Type-safe reading
List<Integer> ages = context.read("$.users[*].age", List.class);

// Generic type reference
TypeRef<List<Map<String, Object>>> typeRef = new TypeRef<List<Map<String, Object>>>() {};
List<Map<String, Object>> users = context.read("$.users", typeRef);

// Access underlying data
Map<String, Object> jsonData = context.json();
String jsonString = context.jsonString();

Writing Operations

Modifying the parsed JSON document by setting, adding, deleting, or transforming values.

/**
 * Sets a value at the specified path
 * @param path JsonPath expression
 * @param newValue Value to set
 * @param filters Optional predicates for filtering
 * @return Updated DocumentContext
 */
public DocumentContext set(String path, Object newValue, Predicate... filters);

/**
 * Sets a value using compiled JsonPath
 * @param path Compiled JsonPath instance
 * @param newValue Value to set
 * @return Updated DocumentContext
 */
public DocumentContext set(JsonPath path, Object newValue);

/**
 * Transforms values using a mapping function
 * @param path JsonPath expression
 * @param mapFunction Function to transform values
 * @param filters Optional predicates for filtering
 * @return Updated DocumentContext
 */
public DocumentContext map(String path, MapFunction mapFunction, Predicate... filters);

/**
 * Transforms values using compiled JsonPath
 * @param path Compiled JsonPath instance
 * @param mapFunction Function to transform values
 * @return Updated DocumentContext
 */
public DocumentContext map(JsonPath path, MapFunction mapFunction);

/**
 * Deletes values at the specified path
 * @param path JsonPath expression
 * @param filters Optional predicates for filtering
 * @return Updated DocumentContext
 */
public DocumentContext delete(String path, Predicate... filters);

/**
 * Deletes values using compiled JsonPath
 * @param path Compiled JsonPath instance
 * @return Updated DocumentContext
 */
public DocumentContext delete(JsonPath path);

/**
 * Adds a value to an array at the specified path
 * @param path JsonPath expression pointing to array
 * @param value Value to add
 * @param filters Optional predicates for filtering
 * @return Updated DocumentContext
 */
public DocumentContext add(String path, Object value, Predicate... filters);

/**
 * Adds a value to an array using compiled JsonPath
 * @param path Compiled JsonPath instance pointing to array
 * @param value Value to add
 * @return Updated DocumentContext
 */
public DocumentContext add(JsonPath path, Object value);

/**
 * Adds or updates a property in an object
 * @param path JsonPath expression pointing to object
 * @param key Property name
 * @param value Property value
 * @param filters Optional predicates for filtering
 * @return Updated DocumentContext
 */
public DocumentContext put(String path, String key, Object value, Predicate... filters);

/**
 * Adds or updates a property using compiled JsonPath
 * @param path Compiled JsonPath instance pointing to object
 * @param key Property name
 * @param value Property value
 * @return Updated DocumentContext
 */
public DocumentContext put(JsonPath path, String key, Object value);

/**
 * Renames a property key
 * @param path JsonPath expression pointing to object containing the key
 * @param oldKeyName Current key name
 * @param newKeyName New key name
 * @param filters Optional predicates for filtering
 * @return Updated DocumentContext
 */
public DocumentContext renameKey(String path, String oldKeyName, String newKeyName, Predicate... filters);

/**
 * Renames a property key using compiled JsonPath
 * @param path Compiled JsonPath instance pointing to object
 * @param oldKeyName Current key name
 * @param newKeyName New key name
 * @return Updated DocumentContext
 */
public DocumentContext renameKey(JsonPath path, String oldKeyName, String newKeyName);

Usage Examples:

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.MapFunction;

String json = "{ \"users\": [{ \"name\": \"Alice\", \"age\": 30 }], \"metadata\": {} }";
DocumentContext context = JsonPath.parse(json);

// Set values
context.set("$.users[0].age", 31);
context.set("$.metadata.lastUpdated", "2024-01-01");

// Delete values
context.delete("$.users[0].age");

// Add to arrays
context.add("$.users", Map.of("name", "Bob", "age", 25));

// Add/update object properties
context.put("$.metadata", "version", "1.0");
context.put("$.metadata", "author", "System");

// Rename keys
context.renameKey("$.users[0]", "name", "fullName");

// Transform values with mapping function
context.map("$.users[*].age", new MapFunction() {
    public Object map(Object currentValue, Configuration configuration) {
        return ((Integer) currentValue) + 1; // Add 1 to all ages
    }
});

// Lambda version (Java 8+)
context.map("$.users[*].name", (current, config) -> 
    ((String) current).toUpperCase());

// Get updated JSON
String updatedJson = context.jsonString();

Evaluation Control

Methods for controlling the evaluation process with limits and listeners.

/**
 * Limits the number of results returned by evaluation
 * @param maxResults Maximum number of results to return
 * @return ReadContext with limit applied
 */
public ReadContext limit(int maxResults);

/**
 * Adds evaluation listeners to monitor path evaluation
 * @param listener Listeners to add for evaluation events
 * @return ReadContext with listeners added
 */
public ReadContext withListeners(EvaluationListener... listener);

Usage Examples:

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.EvaluationListener;

DocumentContext context = JsonPath.parse(largeJsonArray);

// Limit results to first 10 matches
List<String> limitedResults = context
    .limit(10)
    .read("$.items[*].name");

// Add evaluation listener
List<String> names = context
    .withListeners(new EvaluationListener() {
        public EvaluationContinuation resultFound(FoundResult found) {
            System.out.println("Found: " + found.result() + " at " + found.path());
            return EvaluationContinuation.CONTINUE;
        }
    })
    .read("$.users[*].name");

Advanced Reading Operations

Additional ReadContext methods for performance optimization and monitoring.

/**
 * Limits the number of results returned from path evaluation
 * @param maxResults Maximum number of results to return
 * @return ReadContext with result limit applied
 */
public ReadContext limit(int maxResults);

/**
 * Adds evaluation listeners to monitor path evaluation progress
 * @param listeners Listeners to receive evaluation callbacks
 * @return ReadContext with listeners attached
 */
public ReadContext withListeners(EvaluationListener... listeners);

Usage Examples:

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.EvaluationListener;
import java.util.List;

String json = "{ \"items\": [" +
    "{ \"id\": 1, \"name\": \"Item 1\" }," +
    "{ \"id\": 2, \"name\": \"Item 2\" }," +
    "{ \"id\": 3, \"name\": \"Item 3\" }," +
    "{ \"id\": 4, \"name\": \"Item 4\" }," +
    "{ \"id\": 5, \"name\": \"Item 5\" }" +
    "] }";

DocumentContext context = JsonPath.parse(json);

// Limit results to first 3 items
List<Object> limitedResults = context.limit(3).read("$.items[*]");
// Returns only first 3 items

// Create evaluation listener
EvaluationListener listener = new EvaluationListener() {
    @Override
    public EvaluationContinuation resultFound(FoundResult found) {
        System.out.println("Found result at index " + found.index() + 
                          " with path " + found.path() + 
                          ": " + found.result());
        
        // Continue evaluation for all results
        return EvaluationContinuation.CONTINUE;
        
        // Or abort after first result
        // return EvaluationContinuation.ABORT;
    }
};

// Use listener to monitor evaluation
List<Object> monitoredResults = context.withListeners(listener).read("$.items[*].name");

// Combine limit and listeners
List<Object> combinedResults = context
    .limit(2)
    .withListeners(listener)
    .read("$.items[*]");

Evaluation Listener Interface

Interface for monitoring JsonPath evaluation progress and controlling execution.

/**
 * Interface for receiving callbacks during path evaluation
 */
public interface EvaluationListener {
    /**
     * Called when a result is found during path evaluation
     * @param found Information about the found result
     * @return Continuation instruction for evaluation
     */
    EvaluationContinuation resultFound(FoundResult found);
    
    /**
     * Enumeration controlling evaluation continuation
     */
    public enum EvaluationContinuation {
        /** Continue evaluation to find more results */
        CONTINUE,
        /** Abort evaluation immediately */
        ABORT
    }
    
    /**
     * Interface providing information about a found result
     */
    public interface FoundResult {
        /**
         * Index of the result in the evaluation sequence
         * @return Zero-based index of this result
         */
        int index();
        
        /**
         * Path to the found result
         * @return JsonPath string to this result
         */
        String path();
        
        /**
         * The actual result value
         * @return Found result object
         */
        Object result();
    }
}

Usage Examples:

import com.jayway.jsonpath.EvaluationListener;
import com.jayway.jsonpath.EvaluationListener.EvaluationContinuation;
import com.jayway.jsonpath.EvaluationListener.FoundResult;

// Simple logging listener
EvaluationListener loggingListener = new EvaluationListener() {
    @Override
    public EvaluationContinuation resultFound(FoundResult found) {
        System.out.println("Result " + found.index() + ": " + found.result());
        return EvaluationContinuation.CONTINUE;
    }
};

// Early termination listener (stops after 3 results)
EvaluationListener earlyTerminationListener = new EvaluationListener() {
    @Override
    public EvaluationContinuation resultFound(FoundResult found) {
        if (found.index() >= 2) {  // Stop after 3 results (0, 1, 2)
            return EvaluationContinuation.ABORT;
        }
        return EvaluationContinuation.CONTINUE;
    }
};

// Filtering listener (only continues for specific results)
EvaluationListener filteringListener = new EvaluationListener() {
    @Override
    public EvaluationContinuation resultFound(FoundResult found) {
        Object result = found.result();
        if (result instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) result;
            Object price = map.get("price");
            if (price instanceof Number && ((Number) price).doubleValue() > 10.0) {
                System.out.println("Expensive item found: " + result);
            }
        }
        return EvaluationContinuation.CONTINUE;
    }
};

// Use listeners with document context
DocumentContext context = JsonPath.parse(json);
List<Object> results = context
    .withListeners(loggingListener, filteringListener)
    .read("$.store.book[*]");

ParseContext Interface

Interface for creating DocumentContext instances with different parsing configurations.

/**
 * Interface for parsing JSON from various sources
 */
public interface ParseContext {
    /**
     * Parse JSON string
     * @param json JSON string to parse
     * @return DocumentContext for operations
     */
    DocumentContext parse(String json);
    
    /**
     * Parse JSON object
     * @param json Parsed JSON object
     * @return DocumentContext for operations
     */
    DocumentContext parse(Object json);
    
    /**
     * Parse from input stream
     * @param json Input stream containing JSON
     * @return DocumentContext for operations
     */
    DocumentContext parse(InputStream json);
    
    /**
     * Parse from input stream with charset
     * @param json Input stream containing JSON
     * @param charset Character encoding to use
     * @return DocumentContext for operations
     */
    DocumentContext parse(InputStream json, String charset);
    
    /**
     * Parse from file
     * @param json File containing JSON data
     * @return DocumentContext for operations
     * @throws IOException If file cannot be read
     */
    DocumentContext parse(File json) throws IOException;
    
    /**
     * Parse UTF-8 encoded bytes
     * @param json Byte array containing UTF-8 JSON
     * @return DocumentContext for operations
     */
    DocumentContext parseUtf8(byte[] json);
}

Install with Tessl CLI

npx tessl i tessl/maven-com-jayway-jsonpath--json-path

docs

configuration.md

core-operations.md

document-context.md

filtering.md

index.md

type-handling.md

tile.json