Open SplicePHP opened 10 years ago
I tried and tried.. finally a coworker pointed me to this elegant shortcut, but I could not get it to fit in the project (either in function parse()
or somewhere in function valueChanged()
. Maybe someone will find the better way:
const normalize = (val) => {
try {
return JSON.parse(val);
} catch (err) {
return val;
}
};
const data = normalize(inputField.value);
const jsonString = JSON.stringify(data);
which I mashed down to just:
function normalize(str) {
let normalized = null;
try {
normalized = JSON.parse(str);
}
catch (e) {
normalized = str;
}
return JSON.stringify(normalized);
}
The issue I was bumping into was that once a string is made a string (stringify to get its quotes), then the next time the user changes that value, the quotes get escaped .. .
Hi, Adding double quotes and escaping string yourself is a hassle. Strings should also be auto escaped if needed. Here is my proposed solution.
(it is a bit dirty and might need some work)
replace parse function with:
Now strings will be escaped and quoted automatically. If the parameter added is an array object string number or bool it still perceived as such. Only when it can't parse the data it will assume it is a string that needs formatting and escape it automatically.