"JavaScript throws an 'Undefined' error when trying to access a basic

I am struggling with a basic set of HTML and JS files that are not functioning properly, and I can't seem to pinpoint the issue:

<html>
 <head>
  <script type="text/javascript" src="data.json"></script>
 </head>
 <body>
 </body>
</html>
var data = '{"name" : "Phil Powell"}';
alert(data + ' ' + data.name + ' ' + data.type);

Every time I attempt to open this setup, I consistently encounter the same error message:

{"name" : "Phil Powell"} undefined undefined

I can't understand what I'm doing incorrectly. My goal is simply to parse an external JSON file, but I cannot achieve it.

Your assistance would be greatly appreciated.

Thank you

Answer №1

let info = '{"title" : "John Doe"}';

delete the surrounding single quote as indicated in the instruction below

let info = {"title" : "John Doe"};

Answer №2

Your information is currently in string format. You must convert it to an object in order to access it by key.

var data = '{"name" : "Sarah Miller","occupation":"engineer"}';
var obj = JSON.parse(data);

console.log(data + ' ' + obj.name + ' ' + obj.occupation);

Answer №3

Eliminate unnecessary quotation marks:

let information = {"name" : "Sara Smith", "age" : 25};
console.log(information.name + ' ' + information.age);

Answer №4

I am glad to provide this information

var info = {"name" : "Samantha Smith", "type" : "Tool"};
console.log(info['name'] + ' ' + info['type']);

var info = '{"name" : "Samantha Smith", "type" : "Tool"}';
var object = JSON.parse(info);
console.log(object.name + ' ' + object.type);

Answer №5

There are two ways to ensure it functions properly:

1. Eliminating single quotes from the string

var info = '{"name" : "Phil Powell","type":"something"}';

Instead of that, utilize the following:

var info = {"name" : "Phil Powell","type":"something"};

console.log(info.name, info.type);

2. Transform your string into a JSON object using JSON.parse()

`var information = '{"name" : "Phil Powell","type":"something"}';`

`var obj = JSON.parse(information);`

`console.log(information.name, information.type);`

Answer №6

Have you attempted using src= data.js as suggested?

<script type="text/javascript" src="data.js"></script>

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

Upon initiating npm start in my React application, an error was encountered: internal/modules/cjs/loader.js:834

Upon downloading my React course project, I proceeded to install dependencies and run npm start. To my dismay, I encountered the following error: PS C:\Users\Marcin & Joanna\Desktop\react-frontend-01-starting-setup> npm start &g ...

Assigning a new classification to the primary object in the evolving array of objects

I'm working with an element that loops through all the objects using v-for and has a CSS class named top-class{}... I need to dynamically add the top-class to the first object (object[0]) and update it based on changes, removing the old top-class in t ...

Retrieve the selected option from the dropdown menu in the specified form

What should I do if I have numerous products and want users to be able to add new dropdown boxes dynamically? When the submit button is clicked, only the value of "category[]" within the form should be retrieved. https://i.stack.imgur.com/v1fnd.png Below ...

Concealing axis lines within the initial circular grid or opting not to include them

Is there a way to incorporate some whitespace within the center circle of the radar chart? I'm aiming for the axis to commence at 1 radius (the initial circular line) or perhaps have the stoke set to 0 for the primary radius. Any assistance would be g ...

Encountering difficulties reaching $refs within component method

Trying to access a ref defined within a template when an element is clicked. Here's the HTML: <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protectio ...

When an onClick event is triggered in jQuery, generate a certain number of div blocks based on the available list items, such as image source and heading text

Is it possible to generate input fields dynamically based on a dynamic list with checkboxes, labels, text, images, etc.? I currently have a working solution for checkboxes and labels using the code snippet below: let $checkboxContent = $('.checkboxes ...

What is the best way to create floating text that appears when clicked, similar to the mechanics

https://i.stack.imgur.com/nRKG1.jpg Upon clicking the "big cookie" in my game, a popup appears displaying the number of cookies earned (like +276.341 septillion in this image). The popup slowly moves upward and then fades out. I successfully incorporated ...

Creating an illustration with HTML5 from an image

Is it possible to draw on an image by placing a canvas on top of it? I am familiar with drawing on a canvas, but I am facing an issue where clicking on the image does not trigger the canvas for drawing. How can I resolve this? This is how my HTML looks: ...

Connecting a text input in a nested component to the data passed down from its parent component in VueJS

My VueJS setup involves a child component sending data to a parent component, which then tries to route the data to a sibling of the child to create new components. I'm using a dictionary to group the data and push it into an array. The array is then ...

How does the StreamingContext parameter benefit Json.NET Serialization Callbacks?

I've been trying to grasp the purpose of the StreamingContext parameter in Json.NET Serialization Callbacks. Initially, I thought it would provide access to the current JSON tree being read, but it doesn't seem to work that way. Despite experimen ...

How can we display or conceal text indicating the age of a patient based on the value returned from selectedPatient.age in a React application?

Hello, I am looking to dynamically display the age in years on the screen based on the value retrieved from selectedPatient.age, toggling between visible and hidden states. import React, { useContext } from 'react'; import { useHistory } from &ap ...

Can you explain the concept of cross domain and how JSONP fits into the picture?

As a beginner in .net programming, I have created a webservice where JavaScript calls the webservice in my code. I attempted to call it using my phone's browser while on the same network. It works perfectly with localhost, but when trying to call the ...

The Vue.js modal is unable to resize below the width of its containing element

My challenge is to implement the Vue.js modal example in a larger size. I adjusted the "modal-container" class to be 500px wide, with 30px padding and a max-width of 80%. However, I'm facing an issue where the "modal-mask" class, containing the contai ...

Struggling with organizing my code in node.js - it's all over the place and not very reliable. How should I tackle this

Can anyone help me troubleshoot an issue I'm facing with code that writes to the console late or in random order? var request = require('request'); var vFind = 'HelloWorld'; var vFound = false; var vSites = ['http://www.youtu ...

Ways to conceal the TippyJS tooltip so it doesn't show up on video embeds

My website has tooltips enabled, but I am looking to hide the tooltip pop-ups that appear specifically over youtube video embeds. Upon inspecting the webpage, I found the code snippet below that is associated with youtube videos: <div data-tippy-root id ...

Displaying hidden Divs in React Typescript that are currently not visible

I have an array with various titles ranging from Title1 to Title8. When these titles are not empty, I am able to display their corresponding information successfully. Now, my goal is to include a button that will allow me to show all fields. For example, ...

Calling an ajax request to view a JSON pyramid structure

My experience with ajax is limited, so I would appreciate detailed answers. I have a Pyramid application where I need to load information via ajax instead of pre-loading it due to feasibility issues. I want to retrieve the necessary information through a ...

Are you in the business of building JavaScript hubs?

I have a unique setup where my express server is in charge of handling all routing and session functionalities. I've envisioned a system where logged-in users can connect to distinct "hubs" based on the location of each hub. My idea was to treat each ...

What is the best way for Flask to host the React public files?

When working with React, I created a folder called ./public/assets, and placed an image inside it. Running npm start worked perfectly fine for me. However, after running npm run build in React, I ended up with a ./build folder. To solve this issue, I moved ...

Exploring the elements within array structures

I'm facing an issue with my API response. I'm trying to filter the links and check if the source and target name properties in each object match a specific string. However, I am having trouble accessing the name property. Any suggestions on how I ...