How to get specific part of JSON text

Viewed 912

I have a PHP file that creates a JSON text of my MySQL data.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <title>Sample Page</title>
  <script>
     var settings = {
       "async": true,
       "crossDomain": true,
       "url": "http://www.hotel1.com/Experiment/Api/Json1.php?ID=1",
       "method": "GET"
     }

     $.ajax(settings).done(function (response) {
       console.log(response);
       console.log(response.something.something)
     });
  </script>

Above you can see my code

      [
 {
      "Worker1": {
          "ID :": "1",
         "Username": "Tony"
       }
 }
]

Above you can see my JSON text that is being printed. My problem is I want to know how to select ID from the JSON text in JavaScript. As shown above. When I try to say response.Worker1.ID it give me an error saying ID is undefined.

Can someone help me fix my mistake?

2 Answers

It looks like you are not referencing the json object attribute 'ID' properly. So close! Try the below code and LMK how that works:

[ { "Worker1": { "ID :": "1", "Username": "Tony" } } ]

console.log(response[Worker1].ID)

You need to parse the JSON into a javascript object. Use JSON.parse(), as follows:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <title>Sample Page</title>
  <script>
     var settings = {
       "async": true,
       "crossDomain": true,
       "url": "http://www.hotel1.com/Experiment/Api/Json1.php?ID=1",
       "method": "GET"
     }

     $.ajax(settings).done(function (response) {
       response = JSON.parse(response); // the change is here
       console.log(response);
       console.log(response.something.something)
     });
  </script>

Also bear in mind that your "sample json" returns an array, hence the square brackets []. So to access, you would do response[0].something.

Related