为什么我的json.parse()在iPhone上失败?
-
26-10-2019 - |
题
我正在将钛用于移动应用程序。在应用程序中,服务器返回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”,但解析保持不变。如果您需要更多信息,请告诉我。
谢谢
解决方案
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]);
}
}
不隶属于 StackOverflow