2011-04-09 80 views
0

钛SDK版本:1.6.1
iPhone SDK版本:4.2解析在JSON的错误消息失败

我得到这个响应从我消耗API回来了,我希望有一个弹出 露面每个错误。例如:Desc不能为空。我正在使用JavaScript。

这是JSON中的输出。

{"desc":"can't be blank","value_1":"can't be blank"} 

我试过这个,但它输出每个字符,一个一个。

for (var thekey = 0; thekey < response.length; thekey++) { 

    alert(response[thekey]); 

}; 

如何输出错误?

回答

1

你必须首先JSON解析成一个JavaScript对象,使用JSON.parse

response = JSON.parse(response); 

JSON对象可能无法在旧的浏览器可用,你必须包括json2.js然后。

您无法使用普通的for循环遍历对象。你必须使用for...in

for (var thekey in response) { 
    if(response.hasOwnProperty(thekey)) { 
     alert(response[thekey]); 
    } 
} 

对象的属性是descvalue_1,你不能用数字键访问它们。

+0

完美的作品。谢谢! – 2011-04-09 10:11:08

1

如果response是一个字符串,您需要将它解码为一个对象,然后才能对其执行任何操作。现在你只需循环一个字符串并打印每个字符。

你也可能会想使用

for (var key in responseObject) { 
    var value = responseObject[key]; 
} 

,因为这将是一个对象,你的钥匙是不是数字。