3

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.

3
  • 1
    "A constraint is I cant use JSON"... why? It's a perfect use case for JSON. Change your string to quote the keys and it is valid JSON. Commented Apr 23, 2013 at 8:31
  • Well it's not JSON anyway, since keys in JSON have to be double-quoted.... Where are you getting these strings from? Commented Apr 23, 2013 at 8:31
  • If it were a valid JSON string then you could use JSON.parse('{"required":true, "minlength":2, "maxlength":100}'). Commented Apr 23, 2013 at 8:31

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.