简体   繁体   中英

JSON file is valid but I can't parse it

The valid JSON file below:

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

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

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

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
 }

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]})
}

Try below code

var esr = { 
   "response":{  
      "player_count":6453,
      "result":1
   }
}

var responseText = (JSON.parse(JSON.stringify(esr)));
alert(responseText.response.player_count); //out put 6453

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM