Last active
November 30, 2021 13:51
-
-
Save jasdeepkhalsa/1b506a1462efcc65cd4af860002aa1e4 to your computer and use it in GitHub Desktop.
Stringify JavaScript Objects -> JSON or other parsers safely
This file contains 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
// 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