Skip to content

Instantly share code, notes, and snippets.

@dir
Last active February 14, 2025 03:35
Show Gist options
  • Select an option

  • Save dir/c72595ae795dc4c3db4f8f3181ac5345 to your computer and use it in GitHub Desktop.

Select an option

Save dir/c72595ae795dc4c3db4f8f3181ac5345 to your computer and use it in GitHub Desktop.
Postman Package Library script to convert XML responses to JS/JSON objects

Usage

  1. Add the script to your Postman Package Library, call it whatever you'd like.
  2. Import it in any of your Postman scripts using pm.require("package-name")

Example

const { parse } = pm.require("xml"); // assuming package is named xml

const xmlResponseString = pm.response.text();
const parsedXml = await parse(xmlResponseString);

console.log(parsedXml);

Feel free to use, share, and modify this script however you see fit for your needs.

const xml2js = require("xml2js");
/** @type {Object<string, function>} */
const processors = {
/**
* Converts a string to snake_case
*
* @param {string} str - The string to convert
* @returns {string} The snake_cased string
*/
toSnakeCase: (str) =>
str
.replace(/([A-Z])([A-Z])([a-z])/g, "$1_$2$3") // Handle end of acronym
.replace(/([a-z])([A-Z])/g, "$1_$2") // Handle regular camelCase
.toLowerCase(),
/**
* Parses numbers while preserving empty strings
*
* @param {string} str - The string to parse
* @returns {number | string} Parsed number or original string if empty
*/
parseNumbers: (str) => (str === "" ? str : xml2js.processors.parseNumbers(str)),
};
/**
* XML parser instance with custom processing options
*
* @type {xml2js.Parser}
*/
const Parser = new xml2js.Parser({
tagNameProcessors: [xml2js.processors.stripPrefix, processors.toSnakeCase],
attrNameProcessors: [xml2js.processors.stripPrefix, processors.toSnakeCase],
valueProcessors: [processors.parseNumbers, xml2js.processors.parseBooleans],
attrValueProcessors: [processors.parseNumbers, xml2js.processors.parseBooleans],
explicitArray: false, // Don't create arrays for single elements
ignoreAttrs: false, // Keep attributes
mergeAttrs: true, // Merge attributes with element content
normalize: true, // Trim whitespace
explicitRoot: false, // Don't wrap in a root element
});
/**
* Asynchronously parses an XML string into a JavaScript object
*
* @example
* const { parse } = pm.require("xml");
*
* const xmlString = pm.response.text();
* const parsed = await parse(xmlString); //=> JS object
* // ... do something with the parsed object
*
* @param {string} xmlString - The XML string to parse
* @returns {Promise<Object>} A promise that resolves to the parsed object
* @throws {Error} If parsing fails
*/
const parse = async (xmlString) => Parser.parseStringPromise(xmlString);
module.exports = { Parser, parse };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment