A Java DSL for reading JSON documents using JsonPath expressions, similar to XPath for XML
—
Primary JsonPath functionality for reading JSON documents using path expressions. This covers both static utility methods and compiled path instances for efficient reuse.
Convenience methods for one-time path evaluations on various input sources.
/**
* Reads from a parsed JSON object using a JsonPath expression
* @param json Parsed JSON object (Map, List, or other JSON structure)
* @param jsonPath JsonPath expression string
* @param filters Optional predicates for filtering
* @return Result matching the path expression
*/
public static <T> T read(Object json, String jsonPath, Predicate... filters);
/**
* Reads from a JSON string using a JsonPath expression
* @param json JSON string to parse and query
* @param jsonPath JsonPath expression string
* @param filters Optional predicates for filtering
* @return Result matching the path expression
*/
public static <T> T read(String json, String jsonPath, Predicate... filters);
/**
* Reads from a JSON file using a JsonPath expression
* @param jsonFile File containing JSON data
* @param jsonPath JsonPath expression string
* @param filters Optional predicates for filtering
* @return Result matching the path expression
* @throws IOException If file cannot be read
*/
public static <T> T read(File jsonFile, String jsonPath, Predicate... filters) throws IOException;
/**
* Reads from a JSON input stream using a JsonPath expression
* @param jsonInputStream Input stream containing JSON data
* @param jsonPath JsonPath expression string
* @param filters Optional predicates for filtering
* @return Result matching the path expression
* @throws IOException If stream cannot be read
*/
public static <T> T read(InputStream jsonInputStream, String jsonPath, Predicate... filters) throws IOException;Usage Examples:
import com.jayway.jsonpath.JsonPath;
import java.util.List;
String json = "{ \"users\": [{ \"name\": \"Alice\", \"age\": 30 }, { \"name\": \"Bob\", \"age\": 25 }] }";
// Read single value
String firstName = JsonPath.read(json, "$.users[0].name");
// Result: "Alice"
// Read multiple values
List<String> names = JsonPath.read(json, "$.users[*].name");
// Result: ["Alice", "Bob"]
// Read from file
List<Integer> ages = JsonPath.read(new File("users.json"), "$.users[*].age");
// With filtering
List<String> olderUsers = JsonPath.read(json, "$.users[?(@.age > 25)].name");
// Result: ["Alice"]Compile JsonPath expressions for efficient reuse when the same path will be evaluated multiple times.
/**
* Compiles a JsonPath expression for reuse
* @param jsonPath JsonPath expression string to compile
* @param filters Optional predicates to include in compiled path
* @return Compiled JsonPath instance
* @throws InvalidPathException If the path expression is invalid
*/
public static JsonPath compile(String jsonPath, Predicate... filters);
/**
* Checks if a path expression is definite (points to single item)
* @param path JsonPath expression to check
* @return true if path is definite, false otherwise
*/
public static boolean isPathDefinite(String path);Usage Examples:
import com.jayway.jsonpath.JsonPath;
// Compile path for reuse
JsonPath userNamesPath = JsonPath.compile("$.users[*].name");
// Use compiled path multiple times
List<String> names1 = userNamesPath.read(json1);
List<String> names2 = userNamesPath.read(json2);
List<String> names3 = userNamesPath.read(jsonObject);
// Check if path is definite
boolean isDefinite = JsonPath.isPathDefinite("$.users[0].name"); // true
boolean isIndefinite = JsonPath.isPathDefinite("$.users[*].name"); // falseMethods available on compiled JsonPath instances for reading from various sources.
/**
* Returns the string representation of this JsonPath
* @return path as String
*/
public String getPath();
/**
* Checks if path points to a single item or potentially multiple items
* @return true if path is definite (points to single item)
*/
public boolean isDefinite();
/**
* Applies this JsonPath to a parsed JSON object
* @param jsonObject Container object (Map, List, etc.)
* @return Objects matched by the path
*/
public <T> T read(Object jsonObject);
/**
* Applies this JsonPath to a parsed JSON object with configuration
* @param jsonObject Container object
* @param configuration Configuration to use
* @return Objects matched by the path
*/
public <T> T read(Object jsonObject, Configuration configuration);
/**
* Applies this JsonPath to a JSON string
* @param json JSON string to parse and query
* @return Objects matched by the path
*/
public <T> T read(String json);
/**
* Applies this JsonPath to a JSON string with configuration
* @param json JSON string to parse and query
* @param configuration Configuration to use
* @return Objects matched by the path
*/
public <T> T read(String json, Configuration configuration);
/**
* Applies this JsonPath to a JSON file
* @param jsonFile File containing JSON data
* @return Objects matched by the path
* @throws IOException If file cannot be read
*/
public <T> T read(File jsonFile) throws IOException;
/**
* Applies this JsonPath to a JSON file with configuration
* @param jsonFile File containing JSON data
* @param configuration Configuration to use
* @return Objects matched by the path
* @throws IOException If file cannot be read
*/
public <T> T read(File jsonFile, Configuration configuration) throws IOException;
/**
* Applies this JsonPath to a JSON input stream
* @param jsonInputStream Input stream containing JSON data
* @return Objects matched by the path
* @throws IOException If stream cannot be read
*/
public <T> T read(InputStream jsonInputStream) throws IOException;
/**
* Applies this JsonPath to a JSON input stream with configuration
* @param jsonInputStream Input stream containing JSON data
* @param configuration Configuration to use
* @return Objects matched by the path
* @throws IOException If stream cannot be read
*/
public <T> T read(InputStream jsonInputStream, Configuration configuration) throws IOException;
/**
* Applies this JsonPath to a JSON input stream with explicit charset
* @param jsonInputStream Input stream containing JSON data
* @param charset Character encoding of the stream
* @param configuration Configuration to use
* @return Objects matched by the path
* @throws IOException If stream cannot be read
*/
public <T> T read(InputStream jsonInputStream, String charset, Configuration configuration) throws IOException;Methods for modifying JSON documents using compiled JsonPath instances.
/**
* Sets the value at the path location in the JSON object
* @param jsonObject JSON object to modify
* @param newVal New value to set at path location
* @param configuration Configuration to use
* @return Modified JSON object or path list if AS_PATH_LIST option is set
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
*/
public <T> T set(Object jsonObject, Object newVal, Configuration configuration);
/**
* Transforms values at the path location using a mapping function
* @param jsonObject JSON object to modify
* @param mapFunction Function to transform current values
* @param configuration Configuration to use
* @return Modified JSON object or path list if AS_PATH_LIST option is set
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
*/
public <T> T map(Object jsonObject, MapFunction mapFunction, Configuration configuration);
/**
* Deletes the elements at the path location
* @param jsonObject JSON object to modify
* @param configuration Configuration to use
* @return Modified JSON object or path list if AS_PATH_LIST option is set
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
*/
public <T> T delete(Object jsonObject, Configuration configuration);
/**
* Adds a value to arrays at the path location
* @param jsonObject JSON object to modify
* @param value Value to add to arrays
* @param configuration Configuration to use
* @return Modified JSON object or path list if AS_PATH_LIST option is set
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
* @throws InvalidModificationException If path doesn't point to an array
*/
public <T> T add(Object jsonObject, Object value, Configuration configuration);
/**
* Adds or updates a key-value pair in objects at the path location
* @param jsonObject JSON object to modify
* @param key Key to add or update
* @param value Value for the key
* @param configuration Configuration to use
* @return Modified JSON object or path list if AS_PATH_LIST option is set
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
* @throws InvalidModificationException If path doesn't point to an object
*/
public <T> T put(Object jsonObject, String key, Object value, Configuration configuration);
/**
* Renames a key in objects at the path location
* @param jsonObject JSON object to modify
* @param oldKeyName Current key name to rename
* @param newKeyName New key name
* @param configuration Configuration to use
* @return Modified JSON object or path list if AS_PATH_LIST option is set
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
* @throws InvalidModificationException If path doesn't point to an object or key doesn't exist
*/
public <T> T renameKey(Object jsonObject, String oldKeyName, String newKeyName, Configuration configuration);Usage Examples:
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.MapFunction;
String json = "{ \"users\": [{ \"name\": \"Alice\", \"age\": 30 }, { \"name\": \"Bob\", \"age\": 25 }] }";
Configuration config = Configuration.defaultConfiguration();
// Compile path for write operations
JsonPath agePath = JsonPath.compile("$.users[0].age");
JsonPath usersPath = JsonPath.compile("$.users");
// Set value
Object result = agePath.set(JsonPath.parse(json).json(), 31, config);
// Transform values using mapping function
MapFunction incrementAge = (currentValue, configuration) -> {
if (currentValue instanceof Integer) {
return ((Integer) currentValue) + 1;
}
return currentValue;
};
Object transformed = agePath.map(JsonPath.parse(json).json(), incrementAge, config);
// Add new user to array
Object withNewUser = usersPath.add(JsonPath.parse(json).json(),
Map.of("name", "Charlie", "age", 28), config);
// Add property to first user
JsonPath firstUserPath = JsonPath.compile("$.users[0]");
Object withEmail = firstUserPath.put(JsonPath.parse(json).json(), "email", "alice@example.com", config);
// Rename property
Object renamed = firstUserPath.renameKey(JsonPath.parse(json).json(), "age", "yearsOld", config);
// Delete user
JsonPath secondUserPath = JsonPath.compile("$.users[1]");
Object afterDelete = secondUserPath.delete(JsonPath.parse(json).json(), config);Factory methods for creating parse contexts with different configurations.
/**
* Creates a ParseContext with the specified configuration
* @param configuration Configuration to use for parsing
* @return ParseContext instance
*/
public static ParseContext using(Configuration configuration);
/**
* Creates a ParseContext with the specified JSON provider (deprecated)
* @param provider JsonProvider to use for parsing
* @return ParseContext instance
*/
@Deprecated
public static ParseContext using(JsonProvider provider);Usage Examples:
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.ParseContext;
// Create parse context with custom configuration
Configuration config = Configuration.builder()
.options(Option.SUPPRESS_EXCEPTIONS, Option.ALWAYS_RETURN_LIST)
.build();
ParseContext parseContext = JsonPath.using(config);
DocumentContext doc = parseContext.parse(jsonString);JsonPath expressions use a specific syntax for navigating JSON structures:
$ - Root element.property - Child property (dot notation)['property'] - Child property (bracket notation)[index] - Array element by index[start:end] - Array slice[*] - All array elements or object properties..property - Recursive descent (deep scan)[?(@.property == 'value')] - Filter expression[(@.length-1)] - Expression in bracketsCommon Path Examples:
// Simple property access
"$.store.name" // dot notation
"$['store']['name']" // bracket notation
// Array access
"$.books[0]" // first book
"$.books[-1]" // last book
"$.books[1:3]" // books at index 1 and 2
"$.books[*]" // all books
// Wildcards and recursive
"$.store.*" // all properties of store
"$..price" // all price properties at any level
// Filtering
"$.books[?(@.price < 10)]" // books cheaper than 10
"$.books[?(@.category == 'fiction')]" // fiction books
"$.books[?(@.author =~ /.*Smith/)]" // books by authors named SmithInstall with Tessl CLI
npx tessl i tessl/maven-com-jayway-jsonpath--json-path