DavidDurman / FlexiJsonEditor

JSON editor jQuery plugin
http://jsonmate.com
Other
559 stars 139 forks source link

Auto string detect #24

Open SplicePHP opened 10 years ago

SplicePHP commented 10 years ago

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:

    function parse(str, parsed) {
        var res;
        var fail = false;
        try { res = JSON.parse(str); }
        catch (e) { res = null; if(parsed === true){error('JSON parse failed.')}; fail = true;}
        if(fail === true && parsed !== true){
            var j = $("<div/>").text(str.replace(/\n/g, '\\n'));
            j.text(j.html().replace(/"/g, '&quot;'));
            var val = j.html();
            res = parse('"'+val+'"', true);
        }
        return res;
    }

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.

bronius commented 4 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 .. .