0

I'm a beginner with Json, I follow this tutorial the example I have written is based on the tutorial, but I do not understand it does not work :

<script language="javascript">
var Jtext="{"variables":["var1","var2","var3"]}";
var Jobj=eval("(" + Jtext + ")");
var j=Jobj["variables"];
document.write(j[0]);
</script>

Any helps...

Marwen Trabelsi
  • 4,167
  • 8
  • 39
  • 80
  • NEVER USE EVAL!!.. eval is EVIL!!.. – Vivek Chandra Apr 04 '12 at 21:00
  • I just followed the tutorial.... – Marwen Trabelsi Apr 04 '12 at 21:00
  • are you getting any errors in the browser? – Brian Hoover Apr 04 '12 at 21:02
  • 1
    @zod 1) http://stackoverflow.com/questions/646597/eval-is-evil-so-what-should-i-use-instead 2) http://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/ – Vivek Chandra Apr 04 '12 at 21:05
  • 1
    @zod The only time you want to use it when you want the entire and full power of the programming language in question (for example, if I use `eval` in Python, I accept that I may end up running a Djano web app on the development server). Turns out you almost never, and when you do, you know exactly and don't have to ask. For anything lesser, there are specifically tailored parsers, dead-simple interpreter, perhaps some regexes, or a different (often cleaner and simpler!) way to rewrite the code. –  Apr 04 '12 at 21:07

2 Answers2

0

Remove the evil eval and the double quotes on that JSON Obj.

<script>
    var obj={"variables":["var1","var2","var3"]};
    var j=obj["variables"];
    document.write(j[0]);
</script>

What's wrong in Your example:

var Jtext="{"variables":["var1","var2","var3"]}";

This doesn't work. variables, var1, var2, ... are out of the string, like the syntax highlight shows us here. That leads to a Uncaught SyntaxError: Unexpected identifier.

binarious
  • 4,568
  • 26
  • 35
0

Try:

<script type="text/javascript" language="javascript">

    var Jobj = {'variables':['var1','var2','var3']};

    var j = Jobj.variables;

    document.write(j[0]);

</script>
iambriansreed
  • 21,935
  • 6
  • 63
  • 79