Using JsonPath in Java to Simplify JSON Data Access
This article introduces JsonPath as a DSL for reading JSON data in Java, demonstrates Maven integration, provides code examples for extracting and renaming JSON fields, and mentions the jq command‑line tool for additional JSON manipulation.
JsonPath is a DSL for reading JSON documents, similar to how XPath works with XML.
It is included in the spring-boot-starter-test package and can be added via Maven dependency:
com.jayway.jsonpath
json-path
2.7.0
compileThe library’s GitHub repository is https://github.com/json-path/JsonPath.
Example JSON data and a Java demo show how to load a JSON file, parse it with JsonPath, and read the array of books using the expression "$.store.book[*]" .
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import net.minidev.json.JSONArray;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
public class JsonPathDemo {
public static void main(String[] args) throws IOException {
InputStream resourceAsStream = JsonPathDemo.class.getClassLoader()
.getResourceAsStream("jsonpath.json");
String json = IOUtils.toString(resourceAsStream);
System.out.println(json);
DocumentContext documentContext = JsonPath.parse(json);
JSONArray bookJson = documentContext.read("$.store.book[*]");
System.out.println(bookJson);
}
}To rename keys in a JSON structure, JsonPath provides the renameKey method, allowing different source JSONs to be transformed into a unified model, e.g., changing price to total-price across all book entries.
DocumentContext documentContext = JsonPath.parse(json);
documentContext.renameKey("$.store.book[*]", "price", "total-price");
System.out.println(documentContext.jsonString());Command‑line tools such as jq can also be used for JSON processing.
In summary, JsonPath offers a convenient DSL for JSON manipulation in Java applications, and jq provides a powerful CLI alternative.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.