Groovy中无法从Map取值问题求助(附JSON响应与JSR223代码)
Hey there! Let's work through this issue with accessing values from your JSON-derived Map in Groovy (JSR223). First, let's cover the basics of parsing the JSON correctly, then walk through accessing different parts of your specific response.
Step 1: Make sure your JSON is parsed into a Groovy Map/Collection
The most common mistake here is trying to access values directly from the raw JSON string instead of parsing it first. Use Groovy's JsonSlurper to convert the JSON into a nested structure of Maps and Lists:
import groovy.json.JsonSlurper // Replace this with your actual response source (e.g., vars.get("responseBody") in JMeter) def rawJson = '''{ "id":27, "merchant_id":"39", "title":"Shorts", "subtitle":null, "price":100, "description":null, "images":[ ], "image_thumbs":[ ], "options":[ { "code":"size", "label":"Size", "extra_info":"", "values":[ { "label":"Small", "value":"4" }, { "label":"Medium", "value":"5" } ] } ], "options_available":[ { "combination":[ { "code":"size", "value":"Small" } ] }, { "combination":[ { "code":"size", "value":"Medium" } ] } ], "custom_options":[ ] }''' // Parse the JSON into a usable Groovy object def productData = new JsonSlurper().parseText(rawJson)
Step 2: Accessing top-level values
Once parsed, you can use either dot notation or bracket notation to access top-level fields:
// Get top-level fields def productId = productData.id // or productData["id"] def merchantId = productData.merchant_id // or productData["merchant_id"] def productTitle = productData.title def price = productData.price // Handle null values (like subtitle/description) safely def subtitle = productData.subtitle ?: "No subtitle provided" def description = productData.description ?: "No description available"
Step 3: Accessing nested Lists and Maps
Your JSON has nested arrays (like options and options_available) — here's how to dig into those:
// Get the first option (size) and its details def sizeOption = productData.options[0] def sizeOptionCode = sizeOption.code def sizeOptionLabel = sizeOption.label // Get the "Small" size value from the options def smallSize = sizeOption.values.find { it.label == "Small" } def smallSizeValue = smallSize.value // returns "4" // Access options_available entries def firstAvailableCombination = productData.options_available[0].combination[0] def firstCombinationSize = firstAvailableCombination.value // returns "Small" // Loop through all available combinations (if you need to process all) productData.options_available.each { available -> def sizeValue = available.combination[0].value log.info("Available size: ${sizeValue}") // Replace log.info with your logging/output method }
Common Pitfalls to Avoid
- Forgetting to parse the JSON: If you skip the
JsonSlurperstep and try to access fields on the raw string, you'll get errors — always parse first! - Index out-of-bounds: Check if lists are empty before accessing indices (e.g.,
imagesis empty in your response, soproductData.images[0]will throw an error). Use checks likeif (!productData.images.isEmpty()) { ... } - Null pointer exceptions: Fields like
subtitlearenull— use the Elvis operator (?:) to provide default values as shown earlier.
If you're still having issues, share a snippet of your current JSR223 code and we can troubleshoot further!
内容的提问来源于stack exchange,提问作者Siddish

