Skip to content

Instantly share code, notes, and snippets.

@jasdeepkhalsa
Last active November 30, 2021 13:51
Show Gist options
  • Save jasdeepkhalsa/1b506a1462efcc65cd4af860002aa1e4 to your computer and use it in GitHub Desktop.
Save jasdeepkhalsa/1b506a1462efcc65cd4af860002aa1e4 to your computer and use it in GitHub Desktop.
Stringify JavaScript Objects -> JSON or other parsers safely
// Adapted from the Axios HTTP library
// https://github.com/axios/axios/blob/76f09afc03fbcf392d31ce88448246bcd4f91f8c/lib/defaults.js#L29
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
const trim = (str) => {
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
}
const stringifySafely = (rawValue: string | object, parser: Function, encoder: Function): string => {
// If it's already stringified JSON, convert it back into an object first
// Using JSON.parse by default, or a specified parser
if (utils.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
// Return the value with any spaces trimmed
return trim(rawValue);
} catch (e) {
// Throw any error, apart from the stringifySafely
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
// If it's already an object, stringify it
// Using JSON.stringify by default, or a specified encoder
return (encoder || JSON.stringify)(rawValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment