JSON is used to read data from a web server, also it is used to display the data in a web page. In this blog we will be accessing the values of JSON object with the help of the jquery's getJSON() method. GetJSON() method is used to load the JSON encoded data from the server.
GetJSON() method syntax:
jQuery.getJSON( url[,data][,success] )
|
where, url – is a string which contains the URL to which the request is to be sent.
Data – an object that is to be sent to the server along with the request.
Success – is a callback function that is executed when the request succeeds.
Pass the following JSON string and save a file “data.json”:
{
"countries":[
{
"cityName" :"Aachen, DE",
"location" : "EUR|DE|GM011|AACHEN",
"country" : "Germany",
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
}
},{
"cityName" :"Aalborg, DK",
"location" : "EUR|DK|DA007|AALBORG",
"country" : "Denmark",
"address": {
"streetAddress": "452b Street",
"city": "New York"
}
}
]
}
js code:
$(function(){
var url = "data.json";
$.getJSON( url , function( data ) {
var items = [];
$.each( data.countries, function( key, val ) {
items.push( "<li id='" + key + "'>" + "<ul>" + "<li>City Name: " + val.cityName + "</li>" + "<li>Location: " + val.location + "</li>" + "<li>Country: " + val.country + "</li>"+ "<li>"+ "streetAddress : " + val.address.streetAddress + "</li>" + "</ul>" + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
});
Next you are required to create an HTML page to get the object values displayed. That's all.
Happy Coding :)
0 Comment(s)