0

可能重复:
如何访问此 JSON 值?

我从列表的 Spring mvc 控制器生成了以下 json 字符串。如何访问 jquery 中的 holidayName 属性。

[{"holidayId":1,"holidayName":"Raksha Bandhan",
  "holidayStartDate":"Aug 2, 2012 12:00:00 AM",
  "holidayEndDate":"Aug 2, 2012 12:00:00 AM"},
 {"holidayId":2,"holidayName":"Independence day",
  "holidayStartDate":"Aug 15, 2012 12:00:00 AM",
  "holidayEndDate":"Aug 15, 2012 12:00:00 AM"}]
4

2 回答 2

1
 var data=[
           {"holidayId":1,"holidayName":"Raksha Bandhan","holidayStartDate":"Aug 2, 2012 12:00:00 AM","holidayEndDate":"Aug 2, 2012 12:00:00 AM"},
           {"holidayId":2,"holidayName":"Independence day","holidayStartDate":"Aug 15, 2012 12:00:00 AM","holidayEndDate":"Aug 15, 2012 12:00:00 AM"}
         ]

   $.each(data,function(index,item){       
        alert(item.holidayName)      
   });

工作样本:http: //jsfiddle.net/5egk2/1/

于 2012-07-23T11:31:19.393 回答
0

我不熟悉 Spring MVC,但是您应该小心观察您正在使用的起始“json string”是string还是object

如果它是一个字符串,您需要首先使用 $.parseJSON 作为@Felix 提到的。

如果它已经是一个对象,那么您可以像@Shyju 所做的那样直接访问它,或者像这样没有每个循环:

var input = 
    [
        {
            "holidayId": 1,
            "holidayName": "Raksha Bandhan",
            "holidayStartDate": "Aug 2, 2012 12:00:00 AM",
            "holidayEndDate": "Aug 2, 2012 12:00:00 AM"
        },
        {
            "holidayId": 2,
            "holidayName": "Independence day",
            "holidayStartDate": "Aug 15, 2012 12:00:00 AM",
            "holidayEndDate": "Aug 15, 2012 12:00:00 AM"
        }
    ];

console.log(input[0]['holidayName']); //'Raksha Bandhan'
console.log(input[1]['holidayName']); //'Independence Day'

​http://jsfiddle.net/zTeX2/

于 2012-07-23T11:43:23.027 回答