1

我正在将 Titanium 用于移动应用程序。在应用程序中,服务器返回 JSON 数据,然后由 JSON.parse() 解析。在 Android 上,它运行良好。我还仔细检查了它以确保它对http://jsonformatter.curiousconcept.com/有效

这是我的 JSON 数据:

    {
   "email":"example@mail.com",
   "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 <-> example@mail.com
[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”,但解析保持不变。如果您需要更多信息,请告诉我。

谢谢

4

1 回答 1

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]);
    }
}
于 2011-11-30T20:21:19.247 回答