0

for example my json string is like this :

{
"v1" : [], 
"v2": 2, 
"v3": f()
}

Now the context in which I need to decode this has a definition of f and f() gives right answer in that context(checked via debugger). But JSON.parse(jsonstring) gives me Unexpected token. eval also gives error. What should I do?

See an example Here

1
  • 1
    This isn't a JSON string : " f()". Read json.org Commented Jul 13, 2012 at 13:54

3 Answers 3

2

Why it does not work

Look at the definition of a JSON, it can not contain function calls.

Possible workarounds

One way is to do something like this, return a string of the function you want to call.

{
    "v1" : [], 
    "v2": 2, 
    "v3": "f"
}

Now when you need to access it, you can call the function.

var myJSON = JSON.parse(jsonstring);
var myFunctionResult = window[myJSON.v3]();  //works if global variable

Other option is to change how your code works and make an async script call [jQuery would be getScript, regular JavaScript createElement("script") with appendChild() and use a callback like JSONP does.

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

2 Comments

ok, but I think you understand what I want as result. Please respond accordingly.
Updated it with a possible solution[s].
0

JSON strings cannot contain functions.

JSON is not the same things as a JavaScript object, even though the former is derived from the latter. Ultimately, it is a string.

2 Comments

ok, but I think you understand what I want as result. Please respond accordingly.
I really think it's in your interest to heed what all of us on this page are saying - that even attempting to shoehorn functions into your JSON (which, if you achieved it, would have to be evaluated from strings, because JSON cannot contain functions) is a bad idea. It suggests a flaw in the app design that needs to be addressed. A half-way house might be to mention function names in your JSON, but not the functions themselves.
-1

You should not use any callbacks or function calls in JSON (It is not valid JSON, it is insecure and it is absurd - two last things if you somehow make it work) , there is always way to do it in script.

EDIT: You REALLY don't need to call function from JSON - please return back to "drawing board" and design app to not use this pattern

3 Comments

ok, but I think you understand what I want as result. Please respond accordingly.
Yes, i see you have flaw in app design, "fixed" by function call in JSON
security is orthogonal to the issue, and there's plenty of valid use cases for it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.