Is this JSON valid?

E

eggie5

Is this JSON valid?

I would like to access it like this in my javascript:

var json=eval ('('+json+')');

json.devices.modelNumber and json.devices.image

Would this work?


{
"devices":
[
["modelNumber":"VX3800", "image":"./images/VX3800.jpg"],
["modelNumber":"VX4566", "image":"./images/VX4566.jpg"],
["modelNumber":"VX4536", "image":"./images/VX4536.jpg"],
["modelNumber":"VX4644", "image":"./images/VX4644.jpg"],
["modelNumber":"VX3211", "image":"./images/VX3211.jpg"],
["modelNumber":"VX7857", "image":"./images/VX7857.jpg"],
]
}
 
E

eggie5

I figured it out, this is what I want:

{
"devices":
[
{"modelNumber":"VX3800", "image":"./images/VX3800.jpg"},
{"modelNumber":"VX4566", "image":"./images/VX4566.jpg"},
{"modelNumber":"VX4536", "image":"./images/VX4536.jpg"},
{"modelNumber":"VX4644", "image":"./images/VX4644.jpg"},
{"modelNumber":"VX3211", "image":"./images/VX3211.jpg"},
{"modelNumber":"VX7857", "image":"./images/VX7857.jpg"}
]
}
 
R

RobG

Is this JSON valid?

I would like to access it like this in my javascript:

var json=eval ('('+json+')');

json.devices.modelNumber and json.devices.image

Would this work?


If the JSON text itself was appropriate, yes. But your string has
syntax errors...
{
"devices":
[
["modelNumber":"VX3800", "image":"./images/VX3800.jpg"],

The outer Array literal is OK, but not the inner one - it should be an
object literal. Replace the inner square brackets with curly braces:

{"modelNumber":"VX3800", "image":"./images/VX3800.jpg"},

["modelNumber":"VX4566", "image":"./images/VX4566.jpg"],
["modelNumber":"VX4536", "image":"./images/VX4536.jpg"],
["modelNumber":"VX4644", "image":"./images/VX4644.jpg"],
["modelNumber":"VX3211", "image":"./images/VX3211.jpg"],
["modelNumber":"VX7857", "image":"./images/VX7857.jpg"],

Don't allow trailing commas in Array literals, they are handeled
differently (and sometimes incorrectly) by different browsers, don't
trust to chance.


var jsonTxt = '{ "devices": ['
+ ' {"modelNumber":"VX3800", "image":"./images/VX3800.jpg"}, '
+ ' {"modelNumber":"VX4566", "image":"./images/VX4566.jpg"}, '
+ ' {"modelNumber":"VX4536", "image":"./images/VX4536.jpg"}, '
+ ' {"modelNumber":"VX4644", "image":"./images/VX4644.jpg"}, '
+ ' {"modelNumber":"VX3211", "image":"./images/VX3211.jpg"}, '
+ ' {"modelNumber":"VX7857", "image":"./images/VX7857.jpg"}'
+ ' ]'
+ '}';

var json = eval ('('+jsonTxt+')');
alert( 'Model: ' + json.devices[2].modelNumber // VX4536
+ '\nDevice: ' + json.devices[2].image // ./images/VX4536.jpg
);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top