我试图解析从服务器返回的以下JSON:
{
"plant_1":{
"name":"agi_1",
"growth":[{"d":0,"m":20,"w":2,"n":"10"}]},
"plant_2":{
"name":"agi_2",
"growth":[{"d":0,"m":20,"w":2,"n":"20"}]},
"plant_3":{
"name":"agi_3",
"growth":[{"d":0,"m":20,"w":2,"n":"30"}]},
"plant_4":{
"name":"agi_4",
"growth":[{"d":0,"m":20,"w":2,"n":"40"}]},
"plant_5":{
"name":"agi_5",
"growth":[{"d":0,"m":20,"w":2,"n":"50"}]}
}
(为便于阅读而格式化的代码,没有新行字符)
直接解析JSON会返回以下对象:
如您所见,plant_1.growth
为空,而其他人在数组中有相应的对象。
复制上述字符串并对字符串执行JSON.parse
(例如JSON.parse('string')
)可以正常工作并返回正确的模型。
我不知道发生了什么,因为JSON是有效的。知道如何正确恢复模型吗?
编辑1
我使用Express服务器和Mongoskin查询Mongo数据库并返回请求的数据。以下是数据库查询代码:
db.collection('plants').find({owner : owner}, function(err, result) {
if(err) throw err;
var idx = 1;
result.each(function(err, doc) {
if(doc != null) {
obj['plant_' + idx] = {
name : doc.name,
growth : doc.growth
}
idx = idx + 1;
} else {
console.log(JSON.stringify(obj));
res.send(JSON.stringify(obj));
}
});
});
console.log(JSON.stringify(obj))
:
{"plant_1":{"name":"agi_1","growth":[{"d":0,"m":20,"w":2,"n":"10"}]},"plant_2":{"name":"agi_2","growth":[{"d":0,"m":20,"w":2,"n":"20"}]},"plant_3":{"name":"agi_3","growth":[{"d":0,"m":20,"w":2,"n":"30"}]},"plant_4":{"name":"agi_4","growth":[{"d":0,"m":20,"w":2,"n":"40"}]},"plant_5":{"name":"agi_5","growth":[{"d":0,"m":20,"w":2,"n":"50"}]}}
编辑2
用于请求和处理请求的代码
// Get plants data synchronously
var conn = new XMLHttpRequest();
conn.open("POST", "get-plants", false);
conn.setRequestHeader("Content-type", "application/json");
conn.onreadystatechange = function() {
console.log(conn.responseText) // Line 53
var response = JSON.parse(conn.responseText);
console.log(response); // Line 55
if(conn.readyState == 4 && conn.status == 200) {
if(response != null) {
thatGame.plants = response;
} else {
// empty
console.log('invalid');
}
}
};
conn.send(JSON.stringify({owner : game.state.states['Main'].user}));
console.log(this.plants.plant_1); // Line 74
浏览器console
的屏幕截图。