-1

How can I remove quotes from a JavaScript object literal only by "function" part? For example:

Before

{ "a3" : { "text" : "function(a1,a2) {return a1+a2 }" }

After removing

{ "a3" : { "text" : function(a1,a2) {return a1+a2 } }

P.S: PHP json_encode puts quotes for each value. I need an object function without quotes.

1
  • 4
    Making a couple of assumptions, the correct solution is: Fix your design so that functions start out life as part of your program and are not loaded into it as part of some data. Logic and data should be separated. Commented Mar 22, 2012 at 16:09

2 Answers 2

1

Assuming you trust the source of this content, you can use eval()

someVar = eval('(' + a3.text + ')');
Sign up to request clarification or add additional context in comments.

9 Comments

eval will not work unless he adds a name to his function, and even so, it will not return the function object (I tested it)
@Deleteman It will work if he does something like var someVar = eval('(' + a3.text + ')');
@Bergi eval is not evil if you trust the source and the source is secure (no injection of any kind from another source)
It's not so about security, but about performance and all those scope issues. If you can avoid using it, do it. [1]
@Bergi Javascript's eval, unlike PHP's is very fast. I don't know of it's scoping issues, I assume it just executes everything in the scope of the function you call it from. I do agree with you. Avoid using it when you can, but there are some situations where it's appropriate. Such as in Douglas Crockford's json2.js JSON parser which uses eval after a bunch of regex checks to make sure nothing non JSON get's through.
|
0

If you have a javascript Object literal, just write / echo

{ "a3" : { "text" : function(a1,a2) {return a1+a2 } }

If you have a JSON string, bear in mind that JSON does not know functions. PHP's json_encode behaviour is only correct.

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.