Rex Rex - 6 months ago 27
Javascript Question

JSON file is valid but I can't parse it

The valid JSON file below:

{
"response": {
"player_count": 6453,
"result": 1
}
}


It doesn't parse when I use (where req is a XMLHttpRequest() object and now suppose to be the JSON file).

JSON.parse(req.responseText)

When I use the console.log(req.responseText) command I get:

{
"response": {
"player_count": 6453,
"result": 1
}
}


So why can't I parse it? (I need to have this be automatic because I will not always know the number of elements each JSON file will have).
When using the following from my Node server (by sending the JSON file to it) All I get is [object Object] when using the code below: This is where the problem lies I think.

app.post('/steam-output', function(req,res){
var params = [];
for (var p in req.body){
params.push({'name':p,'value':req.body[p]})
}
console.log(params);
console.log(req.body);
var context = {};
context.dataList = params;
res.render('steam-output', context);
// steam-output is a handlebars file which is what my Node.js server is running
});

//here is the steam-output.handlebars file
<h1></h1>
<ul>
{{#each dataList}}
<li>{{this.name}}: {{this.value}}
{{/each}}
</ul>


And it also just comes up with [object Object].
Any help on this would be greatly appreciated (please no links to other sites unless they have thorough examples of fixing this).

This problem doesn't happen if it is just this JSON file:

{
"player_count": 6453,
"result": 1
}

Answer

I think you're just iterating the wrong part of the JSON. What happens if you change your for in loop to this?

for (var p in req.body.response){
    params.push({'name':p,'value':req.body.response[p]})
}