1

我目前有一个显示 json 的实时搜索框。但是,我在解决如何显示嵌套 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);

});
});

这是我的 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.......
4

2 回答 2

1

这是你的解决方案

$(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);


});

并尽可能更改 JSON 输出,“图像”<<-- 它需要冒号“:”附近有一点错误,您可以在 [JSfiddle][1] 上找到相同的工作模型

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

于 2016-11-18T16:28:26.800 回答
0

如果您正在谈论如何访问数组中的数组中的 json 对象,您可以使用array[0].object.array[0].object.array[0].array[0]

在您的示例中,您可以使用以下命令选择关闭日“星期一”:

item.shops[0].closed[0]; 

或星期五使用:

item.shops[0].closed[2];

您通过 [-number from 0 to infinity-] 确定数组中的位置

于 2016-11-18T15:29:26.453 回答