Skip to content

Instantly share code, notes, and snippets.

@shameen
Last active October 11, 2018 15:24
Show Gist options
  • Save shameen/a73527326bd458eba1b9576e75a5f971 to your computer and use it in GitHub Desktop.
Save shameen/a73527326bd458eba1b9576e75a5f971 to your computer and use it in GitHub Desktop.
JS: Sanitize JSON data to conform to
/** Make property names conform to javascript property name rules.
* One use case of this is with Kendo UI's Grid, when the column templates are dynamically generated from JSON
*/
sanitizeJsonPropertyNames(arr) {
let _return = [];
for (let i = 0; i < arr.length; i++) {
for (var property in arr[i]) {
//sanitize any property names
let propertyName = property.toString();
propertyName = propertyName.replace(/[\-_]+/g, '_');
propertyName = propertyName.replace(/[^A-Za-z0-9]+/g, '');
if (!propertyName[0].match(/[A-Za-z_]/))
propertyName = '_' + propertyName;
_return[i][propertyName] = arr[i][property];
}
}
return _return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment