Voakie Voakie - 7 months ago 5
Javascript Question

Get variables out of a text string [jQuery]

Here is the text I want to work with (changes often, so the script should always re-gather it from the source):

{"current_players":0,"alive":0,"spectators":0,"max_players":64,"gamemode":"Free For All","start_time":1461428927679}


I basically want to create a table that will visually display these variables.
It should look something like this in the end:



/* Ignore me */
td {
border: 1px solid grey;
}
/* Stop ignoring */

<table>
<tr>
<td>Players</td>
<td>X</td><!-- Variable of "current_players" -->
</tr>
<tr>
<td>Gamemode</td>
<td>FFA</td><!-- Variable of "gamemode" -->
</tr>
<tr>
<td>...</td>
<td>X</td><!-- And so on... ->
</tr>
</table>





Any ideas how I can do that?

Thanks in advance.

Answer

You have to parse the json using Javascript. See http://www.json.org/js.html and see http://json.org/example.html. If you are using any server side language, you have extensions to parse json easily in them. Php, for example has a built in function to handle json.

var myJSONObject = {
   "current_players": 0,
   "alive": 0,
   "spectators": 0,
   "max_players": 64,
   "gamemode": "Free For All",
   "start_time": 1461428927679
};
document.getElementById("players").innerHTML = myJSONObject.current_players;
document.getElementById("gamemode").innerHTML = myJSONObject.gamemode;
document.getElementById("alive").innerHTML = myJSONObject.alive;
document.getElementById("max_players").innerHTML = myJSONObject.max_players;
   
<table>
  <tr>
    <td>Players</td>
    <td id='players'></td>
  </tr>
  <tr>
    <td>Gamemode</td>
    <td id='gamemode'></td>
  </tr>
  <tr>
    <td>Alive</td>
    <td id='alive'></td>
  </tr>
  <tr>
    <td>Max Players</td>
    <td id='max_players'></td>
  </tr>
</table>

EDIT :

What you want is auto refresh json from a url, you use this with jquery :-

setInterval(function(){ 
    console.log("Getting scores...");



    $.get( "IPOfYourChoice:88", function( data) {
        myJSONObject = JSON.parse(data);
       document.getElementById("players").innerHTML = myJSONObject.current_players;
        document.getElementById("gamemode").innerHTML = myJSONObject.gamemode;
        document.getElementById("alive").innerHTML = myJSONObject.alive;
        document.getElementById("max_players").innerHTML = myJSONObject.max_players;
    });

}, 3000);

With this code, you can auto refresh the scores every 3000 ms (3 seconds)

Comments