Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Object-like-string to Object

I am storing validation rules in a HTML attribute.

The validation rule in a string literal that looks like this:

'{required:true, minlength:2, maxlength:100}'

To convert it to a javascript object I can use eval(string_literal)

However, eval is...unpleasant.

Is there an alternate to using eval to convert a object like string to an object?

A constraint is I cant use JSON.

like image 606
Django Doctor Avatar asked Jul 20 '26 15:07

Django Doctor


1 Answers

Using eval with well-controlled data from a source you trust is fine. The startup cost of the parser is negligible at worst. Naturally, using eval with poorly-controlled data from sources you don't trust is a Bad Ideatm.

If you don't use eval, I'm afraid there's no real shortcut, you'll have to parse the string yourself. If it's really just a simple list as shown, a couple of split calls with regular expressions would do it, a full-on parser wouldn't be needed.

Quick off-the-cuff example (live copy | source):

(function() {

  var data = '{required:true, minlength:2, maxlength:100}';
  var entries, index, entry, parts;

  entries = data.substring(1, data.length - 2).split(/, ?/);

  for (index = 0; index < entries.length; ++index) {
    entry = entries[index];
    parts = entry.split(/: ?/);
    display("Key '" + parts[0] + "', value '" + parts[1] + "'");
  }

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = String(msg);
    document.body.appendChild(p);
  }

})();

Naturally that's full of assumptions (most notably that values will never be strings containing commas or colons), but again, if the data is simple enough, you can avoid a full parser.

like image 79
T.J. Crowder Avatar answered Jul 22 '26 06:07

T.J. Crowder