使用Java Jayway JSONPath筛选指定条件的JSON属性键值对求助
Hey there, the issue with your original JSONPath expression is that Name.Text is an array—you can’t directly access .content on the array itself; you need to check if any element within that array has the matching content value. Here are a couple of working approaches tailored for Jayway’s JSONPath implementation:
1. Using Nested Filters
This approach checks if the Text array contains any element where content equals 'All-Inclusive Mgmt':
$.Attribute[?(@.Name.Text[?(@.content == 'All-Inclusive Mgmt')] != [])]
The inner filter [?(@.content == 'All-Inclusive Mgmt')] targets matching Text elements, and we verify the result isn’t an empty array (confirming a match was found).
2. Using the any() Predicate (More Readable)
Jayway supports predicate functions like any() to simplify array checks. This expression reads clearly: "find Attribute objects where any item in Name.Text has content equal to 'All-Inclusive Mgmt'":
$.Attribute[?(@.Name.Text.any(item => item.content == 'All-Inclusive Mgmt'))]
Extracting Specific Key-Value Pairs
If you want to retrieve only the Name and content keys from matching Attribute objects, append .[Name, content] to either expression:
$.Attribute[?(@.Name.Text.any(item => item.content == 'All-Inclusive Mgmt'))].[Name, content]
Example Java Code Snippet
To implement this in Java with Jayway JSONPath:
import com.jayway.jsonpath.JsonPath; import java.util.List; import java.util.Map; public class JsonPathQueryExample { public static void main(String[] args) { String json = "{ \"Attribute\":[{ \"Name\": {\"Text\":[{ \"content\":\"All-Inclusive Mgmt\",\"Language\":\"ENG\"}, { \"content\":\"??????\",\"Language\":\"XYZ\"}]}, \"content\": \"Sample Attribute Content\"} ] }"; // Get full matching Attribute objects List<Map<String, Object>> matchingAttributes = JsonPath.read(json, "$.Attribute[?(@.Name.Text.any(item => item.content == 'All-Inclusive Mgmt'))]"); // Or extract only Name and content key-value pairs List<Map<String, Object>> targetKeyPairs = JsonPath.read(json, "$.Attribute[?(@.Name.Text.any(item => item.content == 'All-Inclusive Mgmt'))].[Name, content]"); System.out.println("Matching Attributes: " + matchingAttributes); System.out.println("Target Key-Value Pairs: " + targetKeyPairs); } }
Both approaches work reliably with Jayway JSONPath. The any() method is more intuitive, while the nested filter approach is a solid alternative if you prefer that syntax.
内容的提问来源于stack exchange,提问作者Greg

