0

I'm trying to use an API to get data in JSON form and pass it along to jQuery to do with it what I please.

My JSON looks like

{
    "username": {
        "id": 0001,
        "name": "test",
        "IconId": 000,
        "Level": 00,
        "revisionDate": 00000000
    }
}

From the PHP side this is my code

$json = file_get_contents($url);
$json = json_encode($json);

And from my jQuery I can get data by using

<script type="text/javascript">
  var ar = <?php echo $json ?>;
  document.write(ar);
</script>

However, I want to be able to get specific data from the JSON. name for example.

I tried using jQuery.parseJSON like this

<script type="text/javascript">
  var ar = <?php echo $json ?>;
  ar = jQuery.parseJSON(ar);
  document.write(ar.name);
</script>

And I also tried

<script type="text/javascript">
  var ar = <?php echo $json ?>;
  ar = jQuery.parseJSON(ar);
  document.write(ar[0].name);
</script>

I always either get absolutely nothing (blank page), or I get "undefined".

Thank you.

rohanharrison
  • 233
  • 4
  • 10

2 Answers2

0
data={
    "username": {
        "id": 0001,
        "name": "test",
        "IconId": 000,
        "Level": 00,
        "revisionDate": 00000000
    }
}

console.log(data["username"]["name"]);

//output test
Harminder
  • 141
  • 1
  • 8
0

ar is your object reference. From there, that object has a single property called username. That property stores an object, which has a property called: name.

So, you need:

ar.username.name
Rajesh
  • 24,354
  • 5
  • 48
  • 79
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71