Master the skill of transforming a JSON object to JavaScript and displaying the result on an HTML page

Looking to convert a JSON Object to javascript code. I have a JSON data with 2 columns, and I need to iterate through both columns. Any assistance would be greatly appreciated.

{
    "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 have successfully output the data in the console but struggling to display it in the browser.

Please review the code below.

<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 №1

Try using this code snippet to display content on a web browser:

<html>
<head>
    <title>My Web Page</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 (data) {

                    //console.log(data);
$('div.hotels').append('<div></div>').append("<h3>Hotels</h3>");
        $('div.locations').append('<div></div>').append("<h3>Locations</h3>");
        $.each(data.hotels,function(i,item){
          $('div.hotels').append('<ul></ul>').append("<li>"+item.name+"</li>").append("<li>"+item.description+"</li>");
    });

        $.each(data.location,function(i,item){
          $('div.locations').append('<ul></ul>').append("<li>"+item.name+"</li>");
       });
                }
            });
        })
    </script>

</head>
<body>
<div class="myClass">
<div class="hotels"></div>
<div class="Locations"></div>
</div>

</body>
</html>

Answer №2

Need some code to kick-start your project? Look no further! In this snippet, var json contains the data returned by your ajax call.

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...;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Receiving a mysterious error despite having everything clearly defined in the JavaScript code

Attempting to create a simple jQuery plugin: HTML: <textarea> <p>Hello World!</p> </textarea> jQuery: $.fn.wysiwyg = function (options) { var e = $(this).replaceWith("<iframe>"); console.log($(this)[0].conten ...

Differences between throwing errors, returning error objects, and using callbacks in Javascript

Currently, I am developing an assembler and simulator for a simplistic assembly language that my computer science students use during their classes. The project is being written in JavaScript with the intention of creating a user-friendly interface in the ...

Take a sequence of multiple words and combine them into a single string with hyphens in between

I've been working on a WordPress website and I created a JavaScript function that adds a class to the body tag, allowing for different backgrounds based on the category. It works perfectly fine when the category is a single word, but encounters issues ...

The method gson.fromJson(JsonReader, type) results in a null value

This is an example of testing code for Gson serialization and deserialization Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); JsonWriter jsonWriter = null; try { jsonWriter = new JsonWriter( new ...

Users should always receive a notification, whether it be a success message or an

When I send data to my json and it returns true, a success message should be displayed. If it does not return true, an error message should be shown. The current issue is that the response should indicate whether it was successful or encountered an error. ...

In JavaScript, private variables are not included in the JSON.stringify output

Imagine creating a class called Rectangle with private fields like width and height, initializing them in the constructor. However, when calling JSON.stringify on an instance of this class, it returns an empty object without including the private members. ...

Guide on utilizing Three.js OrbitControl with several objects

I managed to get the orbit control feature working, but I am facing an issue where controlling one object also ends up controlling all three objects on the page. Additionally, pan/zoom functionality does not seem to work at all with the OrthographicCamera. ...

When JavaScript is used to create HTML elements, they mysteriously vanish

I've encountered another issue after resolving the previous one XML file reading problem: always the same result While dynamically creating HTML elements and assigning values read from an XML file, the elements disappear right after creation. Any in ...

disable event listeners on the DOM

I am currently developing a web framework and focusing on integrating XSS prevention measures. I have successfully implemented data escaping for database storage, but now I am faced with the challenge of allowing users to save generated HTML without riskin ...

I'm attempting to implement a hover effect, however, the effect triggers instantly instead of waiting for the hover action

I am in the process of developing my debut jQuery plugin. I'm attempting to incorporate a hover action, however the hover response seems to be triggered instantly. Below is the code for my plugin: (function($){ var Help = function(element, options) ...

Generating a CSV file with data from a collection in Meteor.js

I have successfully written the code to display a list of records on a webpage, but now I want to download it as a CSV (comma separated values) file. Currently, the page is showing the list in the following format: Name Address Description Bob ...

Unable to retrieve value from a hidden input field using JavaScript

My goal is to retrieve a value from a hidden inputbox using JavaScript. However, I am encountering issues where sometimes I receive an "undefined" error and other times there is no output at all. When I utilize alert(document.getElementById('hhh& ...

A guide on formatting data retrieved from an API response using Angular's HttpClient

Struggling with extracting data from an angular HttpClient get request along with an API response structured as follows: (10)[{...}, {...}, {...}, ...] [ 0:{ row: Array(4) 0: "someid" 1: "somename" 2: "someaddress" 3: "somepostcode" ...

Using Node.JS to retrieve values of form fields

I am working with Node.js without using any frameworks (specifically without express). Here is my current code snippet: const { headers, method, url } = req; let body = []; req.on('error', (err) => { console.error(err); }).on(&apos ...

Storing client time data in a database using Node.js

Just starting out with Node.js so bear with me while I learn the ropes. I successfully set up a basic TCP server using the guide here In my current project, users will connect to the server from a web browser and I'm interested in capturing the TCP ...

When attempting to retrieve the data from a JSON file using an XMLHttpRequest, the result that is returned is [object object]

I am currently studying JSON and found a helpful guide on w3schools. Here is the code provided in the guide: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax The guide also includes a sample JSON file: https://www.w3schools.com/js/json_demo.t ...

"Enhance Your Website with jQuery's Interactive Ajax

I have been experimenting with creating an Ajax tooltip using this jQuery plugin: My setup looks something like this: <p id="foottip"> <span href="/last_votes/6">footnote</span>. </p> <script type="text/javascript"> $(f ...

Attempting to develop a student database that will allow for extensive customization and manipulation

Currently in the process of setting up a database (using an ArrayList) to store student information (as an Object Array), I've encountered an issue with my "addStudent()" function. It seems to only utilize the latest array created from calling the fun ...

Altering the background colour of dropdown fields when clicking on a checkbox

How can I make the colors of my dropdown fields match the colors of the text (non-dropdown) fields when they are disabled using a checkbox? This is how my code looks: <form v-on:submit.prevent :disabled="isDisabled(opti ...

What is the best way to utilize the existing MUI state in order to calculate and show column totals?

I am currently in the process of developing an MUI web application to keep track of some personal data. Within this application, I have incorporated the MUI datagrid pro component to efficiently display the data with its robust filtering capabilities. In ...