-
-
Save luan0ap/ccf4e9610baa4cabf49be92d0090e5d7 to your computer and use it in GitHub Desktop.
Sanitize Json String
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
/** | |
* Given you have a JSON string that represents a single object (not array). | |
* SanitizeJsonString will attempt to correct the JSON syntax allowing | |
* it to be parsed. | |
*/ | |
/** | |
* Sanitize user input before attempting to parse the JSON | |
* | |
* @param str | |
* @returns {string} | |
* @constructor | |
*/ | |
var SanitizeJsonString = function(str) { | |
if ( ! str ) return "{}"; | |
return '{' + str | |
// wrap numeric values with quotes | |
.replace(/\:(\s*\d+)/g, ':"$1"') | |
// wrap 'true' values with quotes | |
.replace(/\:(\s*true)/g,':"true"') | |
// wrap 'false' values with quotes | |
.replace(/\:(\s*false)/g,':"false"') | |
// replace 'null' values with empty string | |
.replace(/\:(\s*null)/g,':""') | |
// replace key/value pair separator commas with '@separator@' to avoid confusion | |
// with commas in value strings | |
.replace(/\"\s*?\,\s*?\"/g,'"@separator@"') | |
// strip curly braces | |
.replace(/[{}]/g,'') | |
// split on separator | |
.split("@separator@") | |
// iterate over key value pairs and format them | |
.map( function(element) { | |
// split the key value pair on the colon character | |
var parts = element.split(":"), | |
// format the key | |
key = SanitizeJsonValue(parts[0]), | |
// format the value | |
val = SanitizeJsonValue(parts[1]); | |
return key + ':' + val; | |
}) | |
// reassemble the string | |
.join(",") + '}'; | |
}; | |
/** | |
* Sanitize a JSON value | |
* | |
* @param str | |
* @returns {string} | |
* @constructor | |
*/ | |
var SanitizeJsonValue = function(str) { | |
if ( ! str ) return '""'; | |
return '"' + str | |
// strip off quotes | |
.replace(/^"(.*)"$/, '$1') | |
// remove backslashes | |
.replace(/\\/g,'') | |
// escape slashes | |
.replace(/\//g,'\/') | |
// escape new lines | |
.replace(/\n/g,'\\n') | |
// escape form feed | |
.replace(/\f/g,'\\f') | |
// escape carriage returns | |
.replace(/\r/g,'\\r') | |
// escape double quote | |
.replace(/\"/g,'\\"') | |
// escape tabs | |
.replace(/\t/g,' ') | |
// trim whitespace | |
.trim() + '"'; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment