I currently have a live search box that displays json. However I am having issues in working out how to display the nested JSON.
I am looking to display the images and the "closed" days. Any help would be appreciated. I have include my java-script and a sample of my json.
$('#search').keyup(function() {
var searchTerm = $(this).val();
var myExp = new RegExp(searchTerm, "i");
$.get("shops.php",function(data,status){
var response='';
var json = $.parseJSON(data);
shops = json.shops;
$.each(shops, function(index, item) {
if(item.shop_name.search(myExp) != -1){
response += "<h2>"+item.shop_name+"</h2>";
response += "<h2>"+item.distance_citycentre.driving_miles+"</h2>";
});
}
$("#content").html(response);
});
});
Here is a sample of my JSON.
{"shops": [
{ "shop_name":"tesco",
"distance_citycentre": {
"driving_miles":"1.5",
"driving_minutes":"3"
},
"closed": [
"monday",
"wedensday",
"friday"
],
"images" [
{
"description":"lake",
"id":"1"
},
{
"description":"ocean",
"id":"2"
}
]
},
{"shop_name":"asda", etc.......
If you're talking about how to access json objects in an array which is in an array, you can access them by using array[0].object.array[0].object.array[0].array[0]
In your example you can select closed day 'monday' by using:
item.shops[0].closed[0];
or friday by using:
item.shops[0].closed[2];
You determine the position in the array by [-number from 0 to infinity-]
Here goes your solution
$(document).ready(function() { var data = '{ "shops":[{"closed":["monday","wedensday","friday"],"images" :[{"description":"lake","id":"1"},{"description":"ocean","id":"2"}]}]}'; var response=''; var json = $.parseJSON(data); shops = json.shops; alert(shops[0].closed[0] + " - "+shops[0].closed[1] + " - " +shops[0].closed[2]); alert(shops[0].images[0].description + " - "+shops[0].images[0].id); });
And change the JSON Output if possible, There is a little error near "image"<<-- It requires colon ":" You can find the same working model on [JSfiddle][1]
[1]: https://jsfiddle.net/u6exgn7s/ here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.