Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto string detect #24

Open
SplicePHP opened this issue Jul 11, 2014 · 1 comment
Open

Auto string detect #24

SplicePHP opened this issue Jul 11, 2014 · 1 comment

Comments

@SplicePHP
Copy link

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
Copy link

bronius commented Sep 24, 2020

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 .. .

bronius pushed a commit to getocelot/FlexiJsonEditor that referenced this issue Oct 8, 2020
bronius pushed a commit to getocelot/FlexiJsonEditor that referenced this issue Oct 8, 2020
…g for value without quotes and have it be distinguished from other json types and be automatically quoted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants