I am hoping a second set of eyes can help me find my error. I am creating a basic JSON object and trying to display the values in the JSON object. Field 1 displays properly, but fields 2 & 3 display as undefined. Can anyone see what my problem is?
Thanks in advance for your time.
<html>
<head>
<title>String to JSON in JavaScript</title>
<script type="text/javascript">
var mockJSON =
{
"testing" :
[
{ "field1" : "field1" },
{ "field2" : "field2" },
{ "field3" : "field3" }
]
};
function createJSON() {
alert( "field1: " + mockJSON.testing[0].field1 );
alert( "field2: " + mockJSON.testing[0].field2 );
alert( "field3: " + mockJSON.testing[0].field3 );
}
</script>
</head>
<body onLoad="">
<a href="javascript:createJSON();">Build JSON</a>
</body>
</html>
You’re trying to access the same array item which doesn’t have those properties.
i.e.
var mockJSON = {
"testing" : [
{ "field1" : "field1" }, // mockJSON.testing[0].field1 <<<--- mockJSON.testing[0].field2 doesn't exist
{ "field2" : "field2" }, // mockJSON.testing[1].field2
{ "field3" : "field3" } // mockJSON.testing[2].field3
]
};
If you wanted to access those fields without the array you could rewrite the object without it:
var mockJSON2 = {
"testing" : {
"field1" : "field1", // mockJSON.testing.field1
"field2" : "field2", // mockJSON.testing.field2
"field3" : "field3" // mockJSON.testing.field3
}
};
Thank you for the feedback… I see your point. I was referring to elements that did not exist. The field name should be repeated since it is the value in the JSON object. Here is my updated code.
<html>
<head>
<title>String to JSON in JavaScript</title>
<script type="text/javascript">
var mockJSON =
{
"testing" :
[
{ "field1" : "1st iteration" },
{ "field1" : "2nd iteration" },
{ "field1" : "3rd iteration" }
]
};
function createJSON() {
alert( "1: " + mockJSON.testing[0].field1 );
alert( "2: " + mockJSON.testing[1].field1 );
alert( "3: " + mockJSON.testing[2].field1 );
}
</script>
</head>
<body onLoad="">
<a href="javascript:createJSON();">Build JSON</a>
</body>
</html>