简体   繁体   English

使用JQUERY显示嵌套的JSON

[英]Displaying nested JSON using JQUERY

I currently have a live search box that displays json. 我目前有一个显示json的实时搜索框。 However I am having issues in working out how to display the nested JSON. 但是我在研究如何显示嵌套的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. 我已经包含了我的java脚本和我的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. 这是我的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] 如果您正在讨论如何访问数组中数组中的json对象,可以使用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-] 您可以通过[-number从0到无穷大 - 确定数组中的位置 - ]

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] 如果可能的话,更改JSON输出,“image”<< - 它需要冒号“:”你可以在[JSfiddle] [1]上找到相同的工作模型

[1]: https://jsfiddle.net/u6exgn7s/ here [1]: https//jsfiddle.net/u6exgn7s/这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM