如何在含动态唯一键的JSON树中提取首个jobId的JSON Path(适用于Rest Assured+Selenium测试)
Extract First
jobId with Dynamic Top-Level Keys in Rest Assured (Selenium Environment) Got it, let's solve this. Since your JSON's top-level keys are dynamic (they change daily), hardcoding them isn't feasible. Here's the exact JSONPath expression and code you can use in your Rest Assured + Selenium test to grab the first jobId:
Step 1: Use This JSONPath Expression
$.*[0].jobId
Breakdown of the expression:
$.*: Matches all top-level properties (regardless of their dynamic key names) and returns them as an array of objects.[0]: Picks the first object from that array..jobId: Extracts thejobIdvalue from that first object.
Step 2: Implement in Rest Assured + Selenium
Here's a Java code example (since Rest Assured is commonly used with Java in Selenium tests):
// First, get the JSON content (e.g., from a page element or API response) String jsonContent = driver.findElement(By.cssSelector("div#job-results")).getText(); // Initialize Rest Assured's JsonPath parser JsonPath jsonPath = new JsonPath(jsonContent); // Extract the first jobId using the JSONPath expression String firstJobId = jsonPath.getString("$.*[0].jobId"); // Use the extracted jobId as needed in your test System.out.println("First Job ID: " + firstJobId);
Bonus: Filter by Condition (If Needed)
If you ever need the first jobId that meets a specific condition (like the first completed job), you can adjust the JSONPath like this:
$.*[?(@.state == 'COMPLETED')][0].jobId
This will grab the first job where the state is COMPLETED, instead of just the first entry in the JSON.
内容的提问来源于stack exchange,提问作者Abhinav Handa
相关产品推荐
相关产品推荐

