0

So i'm trying to parse this json with javascript and it reads it from the webpage correctly however it just freezes when reaching the JSON.parse.

Here's what the webpage outputs:

{
Players: 18,
maxPlayers: 32,
Map: "jb_summer_redux_v3"
}

Here's what the full code is:

var xhr = new XMLHttpRequest();
var url = "http://in.nickparksdev.com/info.php";
document.write("Loading....");
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    document.write(xhr.responseText);
    var jsonResponse = JSON.parse(xhr.responseText);
    document.write("Test: " + jsonResponse.Players);
  }
}
xhr.send();

Here's what that document.write(xhr.responseText); outputs:

{"Players":19,"maxPlayers":32,"Map":"jb_summer_redux_v3"}

Any help on this would be great :)

2
  • Does the webpage put quotes around Players, maxPlayers, and Map? The first part of your question says it doesn't, but the xhr.responseText shows that it does. Commented Aug 8, 2014 at 1:57
  • What happens if you use console.log() instead of document.write()? Commented Aug 8, 2014 at 1:58

2 Answers 2

2

Your page return HTML not JSON

Output :

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>CSS Players</title>

</head>

<body>
{"Players":15,"maxPlayers":32,"Map":"jb_summer_redux_v3"}</body>
</html>

You have to output only the JSON not HTML.

Sign up to request clarification or add additional context in comments.

1 Comment

He might have noticed this if he'd used console.log() instead of document.write().
0

In my testing, JSON.parse does return the correct object from that string. However, your file is HTML with JSON in it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.