1
<script type="text/javascript">
var X = {
   a: [{name:john, phone:777},{name:john, phone:777},{name:john, phone:777}],
   b: [{name:john, phone:777},{name:john, phone:777},{name:john, phone:777}],
   c: [{name:john, phone:777},{name:john, phone:777},{name:john, phone:777}],
   d: [{name:john, phone:777},{name:john, phone:777},{name:john, phone:777}]


}

var str = JSON.stringify(X);
alert(str);


</script>

What's wrong with this object?? It alerts "Uncaught ReferenceError: john is not defined" How come??

2
  • 9
    john needs to be in quotes as it is a string not a variable identifier Commented May 11, 2011 at 12:12
  • 3
    @meouw You should have made that an answer instead of a comment+1 Commented May 11, 2011 at 12:14

3 Answers 3

8

You need quotes around john. Otherwise it is referring to an variable/object that has not been created:

var X = {
  a: [{name:"john", phone:777},{name:"john", phone:777},{name:"john", phone:777}]
...

Your code would be valid if john was previously defined:

var john = "john";
var X = {
  a: [{name:john, phone:777},{name:john, phone:777},{name:john, phone:777}]
  ...

Now john is a variable representing the string "john", and the JSON is valid.

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

Comments

5

Try name: 'john', you want it to be a string.

If you simply write john, it will be interpreted as a lookup for a variable (including possibly a function) named john. Since it finds no variable with that name, it will say it is not defined.

Same will go with phone, if the value can be something like 123-456-78 (would be interpreted as 123 minus 456 minus 78). If there can be only numbers, your solution is fine as it is now, otherwise use '123-456-78'.

Comments

0

Change X like below. The object attribute names should be single or double quoted. String value should be quoted as well.

var X = {
   a: [{"name":"john", "phone":777},{"name":"john", "phone":777},{"name":"john", "phone":777}],
...
};

1 Comment

Object properties can be both notated as plain characters and as strings. - from Javascript Garden. So name: 'john' is perfectly right.

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.