Exploring ways to display a JavaScript object on click from a .json file

As I delve into the world of javascript and json, I find myself facing a challenge.

I am looking to extract information (using the Get Information function) from a json file within a javascript function triggered by an event. The catch is, I want to accomplish this without relying on jquery or any other library. However, I seem to be hitting a roadblock in my code implementation. Do I need to set up a Request and handle the callback? Or perhaps import additional javascript to properly utilize json data? At this point, all I'm getting is undefined. Any assistance would be greatly appreciated.

The content of the json file:

"hotels": [
    {
        "name": "Hotel Sunny Palms",
        "imgUrl": "imgs/sunny.jpg",
        "rating": 5,
        "price": 108.00
    },
    {
        "name": "Hotel Snowy Mountains",
        "imgUrl": "imgs/snowy.jpg",
        "rating": 4,
        "price": 120.00
    },
    {
        "name": "Hotel Windy Sails",
        "imgUrl": "imgs/windy.jpg",
        "rating": 3,
        "price": 110.00
    },
    {
        "name": "Hotel Middle of Nowhere",
        "imgUrl": "imgs/nowhere.jpg",
        "rating": 4,
        "price": 199.00
    }
]

Here is a snippet of my javascript:

function hot1(){
var text = '{"hotels": [{"name": "Hotel Sunny Palms","imgUrl": "http://www.pruebaswebludiana.xyz/imgs/sunny.jpg","rating": 5,"price": 108.00}]}';
var obj = JSON.parse(text);
document.getElementById("img-container").innerHTML =
obj.imagUrl+ "<br>"+ obj.name+ " " +obj.rating+ " " +obj.price;}

In addition, here is my HTML code snippet:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2" />
  <link rel='stylesheet' href='style.css' type='text/css' media='all' />

</head>
<body>
<nav></nav>
<div class="container">
    <div>
        <ul>
            <li onclick="hot1()">Hotel Sunny Palms</li>
            <li onclick="hot2()">Hotel Snowy Mountains</li>
            <li onclick="hot3()">Hotel Windy Sails</li>
        <li onclick="hot4()">Hotel Middle Of Nowhere</li>
    </ul>
</div>
<div class="banner-section" id="img-container">
</div>


</body>
</html>

Answer №1

Make sure to check your JSON file for an array in the property hotels. You will need to access this array to work with the data. Here is an example of how you can do that:

var jsonData = ...;
var parsedData = JSON.parse(jsonData);
var hotelsArray = parsedData.hotels;
var targetHotel = hotelsArray[0]; // Change the index number to access different hotels
document.getElementById("img-container").innerHTML = 
    targetHotel.imgUrl + "<br/>" + targetHotel.name + " " + targetHotel.rating + " " + targetHotel.price;

Answer №2

{"hotels": [{"name": "Hotel Sunny Palms","imgUrl": "http://www.pruebaswebludiana.xyz/imgs/sunny.jpg","rating": 5,"price": 108.00}]}

The reason you are receiving an undefined message is because you are attempting to retrieve the name (and other attributes) from the main object.

This primary object does not contain those specific attributes. It only holds one attribute: hotels.

The value of the hotels attribute is an array.

Within that array lies an object.

The attributes you seek belong to that particular object within the array.

For example:

obj.hotels[0].name // etc

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

Create a dynamic editing experience using PHP and AJAX, allowing users to make

Is there a way to update my database table without having to refresh the page? I seem to be encountering issues with my script, as the popup and database selection work fine, but nothing happens when I hit submit. It doesn't redirect me to the edit.ph ...

The process of uploading a file through ajax results in it being sent to php://input

---Resolved By making the following adjustment: var request = new XMLHttpRequest(); request.open("POST", $(this).attr('action')); request.send(formData); The issue is now fixed, but I am unsure of the underlying reason. I have not found an exp ...

Angular Ionic: Unable to compare 'value'. Only arrays and iterable objects are permitted for differentiation

I attempted to display a list value and when I logged the value of the list, it appeared exactly how I wanted: unit value {id: 81, name: "3 BR Suite"} unit value {id: 82, name: "3 BR Grande"} unit value {id: 83, name: "Pool Villa&q ...

Python script utilizing curl to make requests to a URL through an API

As a novice Python scripter, I encountered a challenge when trying to integrate a link shortening service. The API documentation provided by the service is in JSON format and requires URL calls using curl. Due to my limited experience, I struggled with i ...

The MUI text input element fails to correctly update the component's state

I have a functioning app that utilizes various inputs. Initially, the dataset is populated with data from an API request as shown below: const [userData, setuserData] = useState([]) const companyuser = useSelector(state=>state.companyuser.currentU ...

Submitting data using AJAX yields results, but the contact form remains untouched

I have created an online quiz using jQuery. My goal is to send the results, along with the user's contact information, to the moderator once they submit it. I have managed to send the result information successfully. However, I am facing an issue whe ...

Gson: utilizing for loading a JSON containing objects

Recently, I've been encountering an issue while trying to import a JSON file using Gson. The problem lies in the fact that while the method toJson is functioning as expected, the structure of objects is not being preserved. My 'Tienda' clas ...

How can I ensure that VueJS only starts loading data after the initial API call has been completed?

After retrieving data from an API, I populate a form in my component. The challenge I am facing is that the watchers are triggered immediately after populating the initial data. I want them to be triggered asynchronously. Additionally, I need to prevent th ...

What could be the reason for JSON.parse not returning the expected outcome?

My code is as follows: var jsonStr = (JSON.stringify(data, ['flightPositions', 'flightId', 'positions', 'lat', 'lon', 'date'], 4)); alert(jsonStr); var jsonObj = JSON.parse(jsonStr); alert(jsonO ...

Using VBA and Selenium to access iframes within HTML with the #document tag

I am currently facing a challenge in accessing the HTML content within two iframes using Selenium Basic in VBA. Due to restrictions on our machines, we are unable to use IE and other tools like Python are not available to us. In the past, I was able to ac ...

Sending additional parameters along with the data obtained from an HTTP request to a method in AngularJS

Within my controller, I have a method that retrieves a JSON file from my API. $scope.get = function (code) { api.get(code) .then(onJsonPart, onError); }; By implementing the above code snippet, I am able to display t ...

Establishing a client cookie will help deter any attempts at re-registering

Due to the inability to run server-side code, I am limited in implementing a PHP session for a registration form. Instead, I have opted to utilize a client cookie to ensure that each person can only register once with a unique email address. After reading ...

Extracting all the details from JSON to Java POJO classes is proving to be challenging

I am currently utilizing the Jackson parser for JSON parsing. My goal is to extract the "props" from the JSON provided below. I need suggestions on what modifications are necessary in the Java POJO class to retrieve the value of "props". The following is t ...

Is it better to use a setter instead of an isMethod with @JsonIgnore in JSON serialization and

Here is a snippet of my custom HouseJPAImpl class: public class HouseJPAImpl implements House { public RoomJPAImpl room; public RoomJPAImpl getRoom(){ return this.room; } public void setRoom(RoomJPAImpl room){ this.room = room; } @Override public bool ...

Transfer information to firebase using a Java class and fetch a single attribute in a different activity

Firebase Database LinkI've been encountering an issue while trying to store data in Firebase using a particular code snippet. Previously, I was able to save data by creating new children under users>uid without any problems. However, now that I am att ...

I've been attempting to develop a React application, but I consistently encounter the following error: "npm ERR! cb() function was never invoked!"

Here is the issue at hand: HP@DESKTOP-1HP83V8 MINGW64 ~/Desktop/Web-Development (master) $ npx create-react-app my-app A new React app is being created in C:\Users\HP\Desktop\Web-Development\my-app. Packages are being installed. ...

NextJs redirection techniquesWould you like to learn the best ways

Currently, I am developing an application using NextJS with Firebase authentication integration. Upon successful authentication, my goal is to retrieve additional customer details stored in a MongoDB database or create a new document for the customer upon ...

Issues with Wordpress Array when used by multiple users - Admin navigation items

Need help removing admin menu items for all users except two. Managed to do it for one user, but struggling with adding a second user to the array: // HIDE ADMIN MENU ITEMS FOR ALL EXCEPT MAIN USER function remove_menus(){ $current_user = wp_get_cur ...

Ways to implement a resize function in Angular JS without relying on the document and window objects

Is there a way to convert the following jQuery code into Angular JS without relying on Document and Window? Can we write the code without utilizing Document.ready and window? ...

Is there a way to accurately retrieve the width of an element within setInterval without any delay?

I'm currently experimenting with increasing a progress bar using the setInterval function. So far, it seems to be functioning properly. var progressBar = $('.progress-bar'); var count = 0; var interval = setInterval(function () { va ...