0

I've got a perfectly correct Json string which gets parsed inside a function's method by using the eval function. When that is done, though, for some unknown reason the first line of a globally defined method is injected inside as one of the array's parameters.

the string being parsed is:

{"id":1,"name":"object1","volume":15,"weight":100}

The parsing line is:

var decoded = eval('(' + encoded + ')');

Once decoded by using the eval() function, I've got the "complementary" attribute decoded['replaceNode'] inside, which contains a global scope function contained inside another file.

I'd consider it a bug, but since the same happens in both firefox and safari, it seems unlikely. More probably I've misunderstood the purpose of eval.

Thank you for your help in advance.

2
  • do you have code which mucks with Object.prototype? that could make all objects have additional attributes. Commented Apr 26, 2012 at 3:54
  • Truth is, eval has one use: running a string as JS code. Not parsing JSON, not parsing anything. Executing arbitrary strings. It doesn't know or care what that string-as-code will do, and if you don't either, you're giving some jackass control over your site. If your JSON is indeed correct, you can use JSON.parse instead. It's built into every decent browser now. Commented Apr 26, 2012 at 4:00

2 Answers 2

4

Don't use eval.

Eval is unsafe and can make attackers execute arbitrary code. Use a JSON library instead.

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

2 Comments

@Blender: and thus he presses the "this answer is not useful" button? Really, the library I linked can be used by a monkey, just read the documentation.
Nice library, tried it and works perfectly. I see what you mean about code injection. Since it can evaluate ANY Javascript object, and functions are objects, it's possible to convert strings back to code and end up executing it if not careful.
0

Setting aside for the moment the pitfalls of using eval()...

I can't reproduce the side-effect you describe.

At a guess, you have loaded a library which overrides eval() to "augment" the result of anything returned by the eval.

2 Comments

Oops my mistake! I thought it was showing me a global scope function, but it was actually a method loaded inside the Object prototype... So logically eval generated me an object with all the methods inside the Object superclass.
Actually, the same seems to happen with the library from github

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.