Harshad Patil Harshad Patil - 4 months ago 14
Javascript Question

learn to convert a json object into a java script and show output in HTML

I need to learn to convert JSON Object to javascript.
In below JSON there are 2 columns, how will I iterate both columns.
Kindly help me out.

{

"hotels": {

"1":{"name": "Taj Residency","description":" Sample description of Taj" },

"2":{"name": "Gulf Zone","description":" Sample description of Gulf Zone"},

"3":{"name": "Silver Resort","description":" Sample description of Silver Resort"},

"4":{"name": "Burj Al Arab","description":" Sample description of Burj Al Arab "},

"5":{"name": "Raffles Dubai","description":" Sample description of Raffles Dubai"},

"6":{"name": "Dubai Heights","description":" Sample description of Dubai Heights"},

"7":{"name": "Classic Tower","description":" Sample description of Classic Tower"},

"8":{"name": "Royal","description":" Sample description of Royal"},

"9":{"name": "Al Arab Residency","description":" Sample description of Al Arab Residency"}

},

"location": {

"1":{"name": "Dubai" },

"2":{"name": "Sharjah"},

"3":{"name": "Abu Dhabi"},

"4":{"name": "Mumbai"}

}

}


I am able to watch my output on the console of the browser, but unable to show it on the browser.

Please check with below code.

<html>
<head>
<title>Assi</title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'jSon.json',
data: '',
dataType: 'json',
success: function (response) {

console.log(response);

}
});
})
</script>

</head>
<body>


</body>
</html>

Answer

Here is some code to get started. Here var json is the response from your ajax request.

var json = '{"hotels": {"1":{"name": "Taj Residency","description":" Sample description of Taj" },"2":{"name": "Gulf Zone","description":" Sample description of Gulf Zone"},"3":{"name": "Silver Resort","description":" Sample description of Silver Resort"},"4":{"name": "Burj Al Arab","description":" Sample description of Burj Al Arab "},"5":{"name": "Raffles Dubai","description":" Sample description of Raffles Dubai"},"6":{"name": "Dubai Heights","description":" Sample description of Dubai Heights"},"7":{"name": "Classic Tower","description":" Sample description of Classic Tower"},"8":{"name": "Royal","description":" Sample description of Royal"},"9":{"name": "Al Arab Residency","description":" Sample description of Al Arab Residency"}},"location": {"1":{"name": "Dubai" },"2":{"name": "Sharjah"},"3":{"name": "Abu Dhabi"},"4":{"name": "Mumbai"}}}';

var obj = JSON.parse(json);

var hotels = obj.hotels;
var locations = obj.location;


/* To access hotels */
for (var i in hotels) {
  var hotel = hotels[i];
  console.log(hotel.name + ":" + hotel.description);
}