2011-11-30 139 views
1

我正在使用Titanium作为移动应用程序。在应用程序中,服务器返回JSON数据,然后由JSON.parse()进行解析。在Android上,它工作正常。我也双重检查它,以确保它是有效的与http://jsonformatter.curiousconcept.com/为什么我的JSON.parse()在iPhone上失败?

这里是我的JSON数据:

{ 
    "email":"[email protected]", 
    "count":6, 
    "0":{ 
     "id":"146996", 
     "user_id":"25069", 
     "item":"item1", 
     "start_my_day":"none", 
     "scheduled":"n", 
     "calendar":"none", 
     "start":"00000000T000000", 
     "end":"00000000T000000", 
     "added":"2011-11-30 06:55:47", 
     "updated":"2011-11-30 06:55:47" 
    }, 
    "1":{ 
     "id":"146988", 
     "user_id":"25069", 
     "item":"item2", 
     "start_my_day":"none", 
     "scheduled":"n", 
     "calendar":"none", 
     "start":"00000000T000000", 
     "end":"00000000T000000", 
     "added":"2011-11-30 06:52:20", 
     "updated":"2011-11-30 06:52:20" 
    } 
    } 

,当我试图检查什么我得到:

var response = JSON.parse(json, function (key, value) { 
    Ti.API.debug('JSON: ' + key + ' <-> ' + value); 
    return value; 
}); 

它看起来像对象“0”没有被解析,因为它的字段是它的父对象的一部分。这里的输出:

[DEBUG] JSON: email <-> [email protected] 
[DEBUG] JSON: count <-> 2 
[DEBUG] JSON: id <-> 146996 
[DEBUG] JSON: user_id <-> 25069 
[DEBUG] JSON: item <-> item1 
[DEBUG] JSON: start_my_day <-> none 
[DEBUG] JSON: scheduled <-> n 
[DEBUG] JSON: calendar <-> none 
[DEBUG] JSON: start <-> 00000000T000000 
[DEBUG] JSON: end <-> 00000000T000000 
[DEBUG] JSON: added <-> 2011-11-30 06:55:47 
[DEBUG] JSON: updated <-> 2011-11-30 06:55:47 
[DEBUG] JSON: 0 <-> [object Object] 
[DEBUG] JSON: id <-> 146988 
[DEBUG] JSON: user_id <-> 25069 
[DEBUG] JSON: item <-> item2 
[DEBUG] JSON: start_my_day <-> none 
[DEBUG] JSON: scheduled <-> n 
[DEBUG] JSON: calendar <-> none 
[DEBUG] JSON: start <-> 00000000T000000 
[DEBUG] JSON: end <-> 00000000T000000 
[DEBUG] JSON: added <-> 2011-11-30 06:52:20 
[DEBUG] JSON: updated <-> 2011-11-30 06:52:20 
[DEBUG] JSON: 1 <-> [object Object] 
[DEBUG] JSON: <-> [object Object] 

从我看到..它不是它应该返回。我试图用引号将计数括起来,将“0”更改为“10”,但解析保持不变。 如果您需要更多信息,请让我知道。

感谢

回答

1

JSON.parse(str, func)被称为为每个属性递归格式化/更换的目的。这不是失败,但你不应该用它来满足你的需求。

如果你想遍历的对象,你最好定期解析JSON和使用循环:

var parsed = JSON.parse(json); 

for(var key in parsed) { 
    console.log(key, parsed[key]); 

    for(var key2 in parsed[key]) { 
     console.log("Nested: ", key2, parsed[key][key2]); 
    } 
} 
+0

在我的生产代码,我没有使用该功能。我只是试图将其用于调试目的,因为我在JSON.parse()行收到异常。但是,事实证明,在某些情况下,我将this.responseText设置为undefined。 – Amy

+0

@annie:我想这是一个不同的问题,除非我是误解。 – pimvdb