This tutorial continues from the previous topic, Inspect the JSON from the response payload. In the sample page where you logged the weather
response to the JS Console, the REST response information didn’t appear on the page. It only appeared in the JS Console. You need to use dot notation and JavaScript to access the JSON values you want. In this tutorial, you’ll use JavaScript to print some of the response to the page.
Note that this section will use a little bit of JavaScript. Depending on your role, you might not use this code much in your documentation, but it’s important to know anyway.
- Getting a specific property from a JSON response object
- Printing a JSON value to the page
- Get the value from an array
- More exercises
Getting a specific property from a JSON response object
JSON wouldn’t be very useful if you always had to print out the entire response. Instead, you select the exact property you want and pull that out through dot notation. The dot (.
) after response
(the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.
As an example, this is the full response from the request made previously:
{ "coord": { "lon": -121.95, "lat": 37.35 }, "weather": [ { "id": 802, "main": "Clouds", "description": "scattered clouds", "icon": "03d" } ], "base": "stations", "main": { "temp": 68.34, "pressure": 1014, "humidity": 73, "temp_min": 63, "temp_max": 72 }, "visibility": 16093, "wind": { "speed": 3.36 }, "clouds": { "all": 40 }, "dt": 1566664878, "sys": { "type": 1, "id": 5122, "message": 0.0106, "country": "US", "sunrise": 1566653501, "sunset": 1566701346 }, "timezone": -25200, "id": 0, "name": "Santa Clara", "cod": 200}
In our scenario (creating a biking app), we want to pull out the wind speed part of the JSON response. Here’s the dot notation you use:
To pull out the wind speed element from the JSON response and print it to the JavaScript Console, add this to your code sample (which you created in the previous tutorial), right below the console.log(response)
line:
console.log("wind speed: " + response.wind.speed);
Your code should look like this:
$.ajax(settings).done(function (response) { console.log(response); console.log("wind speed: " + response.wind.speed);});
Refresh your Chrome browser and see the information that appears in the console:
wind speed: 13.87
' //Xpublisher // contents[1]='
' //TWi // contents[2]='
' //Xeditor // contents[3]='
' // Zoomin contents[1]='
' // Your ad here // contents[1]='
' var i=0 //variable used to contain controlled random number var random //while all of array elements haven't been cycled thru while (i