如何在Ajax中解析JSON对象/数组

时间:2012-07-23 03:46:34

标签: ajax json jsonp arrays

我如何能够从这个来自我的网络服务的json中获取更新的值:

{"listener":{"id":"1","updated":"false"}}

这是我尝试过的:

$.ajax({
       ...
        success : function(data) {            
            console.log("received listener: " + data);            
            var received = JSON.parse(JSON.stringify(data));                              
            var listener = received.listener;  
            var length = listener.length;
            //alert('returned json' + data + ' no. of products received: ' + length);
            console.log('returned json' + listener + ' no. of listener received: ' + length); //it says undefined for the length

            var updated = listener[0].updated;

        }
    });

感谢。

1 个答案:

答案 0 :(得分:2)

首先,这条线没有意义:

var received = JSON.parse(JSON.stringify(data));    

JSON.stringifyJSON结构转换为字符串,而JSON.parse则相反。换句话说:

var received = data.listener; // is equivalent.

其次,received对象

{"id":"1","updated":"false"}

它不是数组,因此它没有length属性。如果您希望获得id对象的received,那么您显然会使用:

var updated = listener.id;

要使您的代码工作data,必须如下所示:

{"listener":[{"id":"1","updated":"false"}]}