I'm trying to parse the following JSON returned from a server:
{
"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"}]}
}
(code formatted for ease of reading, there's no newline char)
Directly parsing the JSON returns the following object :
As you can see, plant_1.growth
is empty, while the others have the corresponding object in the array.
Copying the above string and doing JSON.parse
on the string (e.g. JSON.parse('string')
) works fine and returns the correct model.
I have no idea what's going on, as the JSON is valid. Any idea how to recover the model correctly?
EDIT 1
I'm using Express server and Mongoskin to query the Mongo database and return the requested data. Below is the DB query code :
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));
}
});
});
result of 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"}]}}
EDIT 2
Code used to request and process request
// 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
And a screenshot of browser console
.