Created
September 12, 2022 18:26
-
-
Save mark05e/c3e55c7032cdf50e269e73abe8570f94 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// postman-visualizer-filter-jsonpath | |
// INFO: The postman Visualizer feature allows response data to be displayed in a number of different ways. Pulling in external modules expands the capability even further. This demonstrates how you can use the jsonpath package, in the Visualize tab, to filter the response JSON data returned in your requests. | |
// USAGE: Add this code as a part of pre-req or tests for your postman request | |
// REF: https://www.postman.com/postman/workspace/postman-team-collections/request/1794236-b1c1129a-217b-4b47-8f7c-743dfd896dc4 | |
// REF: https://community.postman.com/t/how-to-filter-response-based-on-specific-custom-field/11026/2 | |
let template = ` | |
<html> | |
<head> | |
<script src="https://cdn.jsdelivr.net/npm/[email protected]/jsonpath.min.js"></script> | |
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script> | |
</head> | |
<body> | |
<div> | |
<div> | |
<input id="filter" style="width:450px;" type="text" placeholder="Example query: $..name.first"> | |
</div> | |
<div> | |
<button id="resetButton" style="background-color:red;color:white;">Reset</button> | |
<input id="showErrors" type="checkbox" value="1"/> | |
<span class="item-text" style="font-family:courier;">Show Evaluation Errors</span> | |
</div> | |
<div id="errors" style="font-family:courier;color:red;display:none;"></div> | |
<div> | |
<p id="content" style="font-family:courier;color:green;font-size:18px;"></p> | |
</div> | |
</div> | |
</body> | |
</html> | |
<script> | |
pm.getData( (error, value) => { | |
const extractedData = jsonpath.query(value, '$'); | |
$(function() { | |
$('#filter').keyup(function() { | |
try { | |
let filteredData = jsonpath.query(extractedData, $(this).val()); | |
$("#content, #errors").empty(); | |
$("#content").append("<pre><code>" + JSON.stringify(filteredData, null, 4) + "</code></pre>"); | |
} catch (err) { | |
console.info(err); | |
$("#errors").empty(); | |
$("#errors").append("<pre><code>" + err + "</code></pre>"); | |
} | |
}); | |
}); | |
$( "#resetButton" ).click(function() { | |
$("#content, #errors").empty(); | |
$("#filter").val(''); | |
$("#content").append("<pre><code>" + JSON.stringify(extractedData, null, 4) + "</code></pre>"); | |
}) | |
}) | |
$(function() { | |
$("#showErrors").on("click",function() { | |
$("#errors").toggle(this.checked); | |
}); | |
}); | |
</script>` | |
pm.visualizer.set(template, pm.response.json()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment