如何在POSTMAN中将仅含值无字段名的响应体捕获到变量中
Got it, this is actually simpler than you might think! When your API returns a raw value with no key/field name (like a plain string, number, boolean, or even a raw JSON primitive), here's exactly how you can capture it into a Postman variable:
Step 1: Navigate to the Tests Tab
Open your target request in Postman, then switch to the Tests tab. This is where we'll add a script that runs automatically right after the request completes.
Step 2: Add the Capture Script
Choose the script that matches your response type:
For Plain Text/Raw String Responses
If your API returns something like my_unique_token_123 (no JSON wrapping, just raw text), use this script to grab the content and store it:
// Fetch the raw text response, trim any extra whitespace/newlines const capturedValue = pm.response.text().trim(); // Store in an environment variable (replace with pm.globals.set for global variables) pm.environment.set("myCapturedVariable", capturedValue);
For JSON Primitive Responses
If your API returns a JSON primitive (like 123, true, or null—no {} or key names), use pm.response.json() to preserve the value's original data type:
// Fetch the JSON primitive value const capturedValue = pm.response.json(); // Store in a variable (use pm.collectionVariables.set for collection-scoped variables) pm.environment.set("myCapturedVariable", capturedValue);
Step 3: Verify It Works
Send your request, then check:
- Go to the Environment (or Globals/Collection) panel to see if
myCapturedVariablehas the correct value - Test it in a subsequent request by referencing it with
{{myCapturedVariable}}
Pro Tips
- If you're unsure about the response format, check the Response tab's Raw view first to confirm if it's plain text or a JSON primitive
- The
trim()method is handy to strip any accidental newline characters or whitespace that might come with the response - If you need to convert a text response to a number, use
Number(pm.response.text().trim())instead of justpm.response.text()
内容的提问来源于stack exchange,提问作者PostMan

