Reputation: 66475
My markup where I get the JSON from using $.parseJSON (after replacing single quotes to double):
<a href="#" data-thumbslide="
[{'slides':
[
{ 'path' : 'img/slider-images/jeep_1.jpg' },
{ 'path' : 'img/slider-images/jeep_2.jpg' },
{ 'path' : 'img/slider-images/jeep_3.jpg', 'fullscreen' : 'img/slider-images/jeep_3-fs.jpg' },
{ 'path' : 'img/slider-images/jeep_4.jpg', 'fullscreen' : 'img/slider-images/jeep_4-fs.jpg'}
],
},
{'info':
[
{ 'blurb' : 'Lorem ipsum dolor sit amet consquiteur' },
{ 'website' : 'http://www.google.co.uk' },
{ 'credits' : 'Warner bros productions' }
]
}]">
<div class="title"><h1>Jeep</h1></div>
</a>
I get an object like this: (result from firebug console log)
[Object { slides=[4]}, Object { info=[3]}]
each object looks something like this:
I can reference the objects like this:
jsonObject[0]['slides'][2].path
jsonObject[1]['info'][0].blurb
However I don't want to rely on the array order by number (so 0 is 'slides' and 1 is 'info') but reference them by name instead and not be reliant on the order. I think I can achieve this with a different JSON structure?
Upvotes: 3
Views: 6295
Reputation: 150080
If you omit the outer []
array brackets and a couple of the {}
brackets you can make 'slides' and 'info' properties of the same (non-array) object:
{
'slides':
[
{ 'path' : 'img/slider-images/jeep_1.jpg' },
{ 'path' : 'img/slider-images/jeep_2.jpg' },
{ 'path' : 'img/slider-images/jeep_3.jpg', 'fullscreen' : 'img/slider-images/jeep_3-fs.jpg' },
{ 'path' : 'img/slider-images/jeep_4.jpg', 'fullscreen' : 'img/slider-images/jeep_4-fs.jpg'}
],
'info':
[
{ 'blurb' : 'Lorem ipsum dolor sit amet consquiteur' },
{ 'website' : 'http://www.google.co.uk' },
{ 'credits' : 'Warner bros productions' }
]
}
And then you can access like this:
jsonObject['slides'][2].path // OR jsonObject.slides[2].path
jsonObject['info'][0].blurb // OR jsonObject.info[0].blurb
The 'slides' property needs to be an array of objects like you have it since each item is of the same type, but I notice that the 'info' object is an array containing objects that are all different. If you'll only have one 'blurb', 'website', 'credits' (or 'whatever') within 'info' you can restructure that part to remove the nested array and instead make 'blurb', etc. properties of a single nested object:
{'slides':
[
{ 'path' : 'img/slider-images/jeep_1.jpg' },
{ 'path' : 'img/slider-images/jeep_2.jpg' },
{ 'path' : 'img/slider-images/jeep_3.jpg', 'fullscreen' : 'img/slider-images/jeep_3-fs.jpg' },
{ 'path' : 'img/slider-images/jeep_4.jpg', 'fullscreen' : 'img/slider-images/jeep_4-fs.jpg'}
],
'info': {
'blurb' : 'Lorem ipsum dolor sit amet consquiteur',
'website' : 'http://www.google.co.uk',
'credits' : 'Warner bros productions'
}
}
Then you can say:
jsonObject['info'].blurb
// or
jsonObject.info.blurb
// or
jsonObject['info']['blurb']
// or
jsonObject.info['blurb']
While access to 'slides' will still be as above.
Upvotes: 3