1

I have a solution now, but it's not the best I think.

function parseEval(value){
    var result = undefined;
    try {
      result = eval(value);
    } catch (e) { }
    return result;
}

So if the value is undefined or contains uninterpretable value the function return undefined.
If contains an existing function name than returns function object
if contains "[1,2,3]" then return int array
if contains "[{ label: "Choice1", value: "value1" },{ label: "Choice2", value: "value2" }]" then return an array of objects
I'm open for any solution because the eval has lot of disadvantages. (performance, security, flexibility, maintainability)

5
  • Where do you see anything about jQuery or jQuery UI here ? -1 Commented Aug 1, 2013 at 11:41
  • Why not use JSON.parse() like everyone else? Commented Aug 1, 2013 at 11:42
  • javascript typeof() ..have a look Commented Aug 1, 2013 at 11:43
  • "flexibility", "maintainability", where do you see that in this code ? You must be a commercial... Commented Aug 1, 2013 at 11:43
  • The jQuery part is that the purpuose of this method is to supply the source option value to jQueryUI autocomplete from html attribute, which must be string. Commented Aug 1, 2013 at 11:49

2 Answers 2

4

If this is an internal function that will never be passed any user-supplied data, this might be the best way to go about things. Otherwise, you would probably be better off using JSON.parse to parse data and look up functions and other non-JSON data in a whitelist:

var someObject = {
    aFunction: function() {},
    anInt: 42
};

function parse(value) {
    var result;
    try {
        return JSON.parse(value);
    } catch(e) {
        return someObject[value];
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. One side question. Now my parse accept only global function. My catch part contains return window[value]. what if I have a jui object contain a Button method, so the jui.Button is an Object, (Function). How to check if the value is jui.Button?
@Péter - you can split the value on . and try and find the value for each section: valueParts = value.split("."); result = someObject; for (var i=0, l=valueParts.length; i<l; i++) { result = result[valueParts[i]]; if (result == null) { return result; } } return result;
0
[{ label: "Choice1", value: "value1" },{ label: "Choice2", value: "value2" }]

isn't json, but assuming that it should be, because you mentioned that in the question,

 console.log(typeof JSON.parse(string)) 

Should work nicely for anything but functions.

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.