Having trouble retrieving information from an external local json file

I'm attempting to display an 'alert' box containing text retrieved from a JSON file. However, I'm facing issues in fetching data from the JSON file and the alert box is not being displayed.

var thebook = JSON.parse(book);

function showAlert() {
  alert(thebook[0].word);
}
<head>
  <script type="text/javascript" src="book.json"></script>
</head>

<body>
  <button onclick="showAlert()">show alert</button>
</body>

Here goes an illustration JSON file

[
  {
    "word" : "cuiller",
    "page" : 23
  },
  
  {
    "word" : "arbre ",
    "page" : 245
  }
]

Answer №1

To set up your JSON in book.json, store it in a variable (e.g. var book as shown below).

var book = [
  {
    "word" : "cuiller",
    "page" : 23
  },

  {
    "word" : "arbre ",
    "page" : 245
  }
];

Make sure to stringify it before parsing or alerting it.

thebook = JSON.parse(JSON.stringify(book));

function showAlert() {
  alert(thebook[0].word);
}

Check out the JSFiddle link for a working example: https://jsfiddle.net/h5knqobs/9/

I hope this explanation is helpful!

Answer №2

To access the resource in your JavaScript code, you must make a request for it rather than just referencing it. One way to do this is by using an XMLHttpRequest, which will retrieve the text from the file. You can then convert this text into an object by using JSON.parse.

An example implementation would be as follows:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
    document.getElementById("demo").innerHTML = myObj.name;
  }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();

For more information on JSON parsing in JavaScript, visit: https://www.w3schools.com/js/js_json_parse.asp

Answer №3

Learn how to access JSON data from a file

var bookData = (function() {
    var json = null;
    $.ajax({
        'async': false,
        'global': false,
        'url': "/book.json",
        'dataType': "json",
        'success': function (data) {
            json = data;
        }
    });
    return json;
})();

Once you have the JSON value stored in a variable, parse it as shown below.

var theBook = JSON.parse(JSON.stringify(bookData));

UPDATE

Here is a revised version of the method

var bookData = null;
$.ajax({
    'async': false,
    'global': false,
    'url': "/test.json",
    'dataType': "json",
    'success': function (data) {
        bookData = data;
    }
});

In your showAlert function, you can simply use bookData[0].word.

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

Strategies for incorporating a JSON variable into the HttpClient query parameters in an Ionic 5 application

Currently using Ionic 5 and attempting to retrieve the IP address of the client user to include it in a URL. Here is my code: this.ipclient = this.httpClient.get("https://api.ipify.org/?format=json"); this.ipclient .subscribe(ipclient => { console.log( ...

Dynamically fetching data with Node.js using Ajax requests

Despite my efforts to scour Google and Stack Overflow, I have been unable to find a reliable method for posting data to my Node.js server. I've noticed conflicting information on various methods, likely due to changes over time. One particular code ...

The useTransition() method in React remains stuck in the isPending state when making API calls from routes in the /pages/api directory

I'm encountering an issue with the useTransition() function where it remains true and never changes back to false. I am attempting to delete a record from MongoDB and after completion, I want to refresh the React Server Component following the guideli ...

What's the best way to update the value of an angular field upon submission?

Could someone please provide instructions on how to update the myName variable when the "submit" button is pressed? Thank you! app.js: app.controller('SomeController', ['$scope', 'emails', function($scope, emails) { emails ...

Tips for accessing an object on the server side in a servlet after it has been sent via retrofit with the @Body annotation

When using retrofit2 on Android, I am sending a Card object and trying to save its data on the server in a JSON file. However, when attempting to retrieve the object's data on the server, the statement below returns null: req.getParameter("job_title" ...

What is the best way to retrieve JSON format using ODATA?

I am aware that ODATA has the capability to return JSON, however I am unsure if I need to use a specific attribute or interface in order to achieve this. My goal is to have my odata service function similarly to ?$format=JSON, but unfortunately my service ...

Python Flask server struggling to find JavaScript and CSS files within index.html when paired with AngularJS frontend

I'm currently working on a simple website project that involves a Python backend running on Flask and an AngularJS frontend. The main issue I am facing is encountering 404 errors when the index template tries to load CSS and JS files. Here's how ...

How can I use jQuery to target elements other than the vertical scrollbar when

Here is how I am utilizing the mouseleave jquery event $(document).ready(function(){ $(document).mouseleave(function(event) { //perform a task }); }); Is there any method to prevent this event from triggering when a user scrolls ...

Obtaining the value for the last JSON object in onPostExecute()

In my AsyncTask, I have successfully parsed the JSON and retrieved values for both objects, such as image and period. However, in the onPostExecute() method, I am only able to get the value for the last json object. Currently, I am only receiving the valu ...

Adjusting Javascript code to convert numerical values in HTML table cells from thousands to millions

Does anyone know how to create a Javascript function for a web report that converts table values to thousands or millions by dividing or multiplying by 1000? The issue is that each value is clickable, meaning it is wrapped in an anchor tag. Is there a wa ...

Guidelines for securing login access where the "IsApproved" field must be true before authorization

During the account registration process, I initially set the default value to false for the field IsApproved. I need to create security rules that allow login only for users with IsApproved:true, and redirect those with IsApproved:false to the accessdenied ...

Issue with parsing an empty array in a Discord bot built with Node.js

Within this API, there exists an empty array marked with a red underline. Sometimes it's void of content, but other times it contains data. My goal is to display Item Spells: there are no effects on this item. when the array is empty. However, instead ...

Issues with Angular ngroute: controllers are not functioning properly

In order to route my application with different themes on the same page, I plan to utilize the ngroute module. Here's an example of how I intend to achieve this: <html> <head> <title>Angular JS Views</title> ...

My goal is to transfer information from the client-side to the server-side upon the user disconnecting from a socket.io connection using Node.js

Is there a way to transmit data from the client side to the server side when a user disconnects from a socket.io connection in Node.js? I attempted creating a new event and calling it within the 'disconnect' event, but it seems impossible since t ...

Ways to evaluate two sentences based solely on the spacing in their dynamic sections

I am tasked with comparing two sentences. The first sentence is stored in a database and looks like this: var text1 = "Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd" The second sentence, which comes from the customer, is as follows: &q ...

What is the best way to adjust the width of a textarea based on its content

How can I dynamically set the width of a React Semantic UI textarea based on its content? Setting min-width doesn't seem to be working. Any suggestions? <Textarea key={idx} defaultValue={formattedText} className="customInpu ...

What is the best way to use jQuery to toggle the visibility of a <panel>?

My objective is to display a panel with two labels on a button click, but I'm facing issues achieving this functionality. When I click on the button (id=Button1), the panel (id=anspanel) should appear, but it remains hidden even after clicking the but ...

Multiple occurrences of trigger events were detected when loading ajax content

In a div I have embedded a paragraph and a button as shown below: <div id="my_div"> <p>This is a paragraph</p> <button class="my_btn">Click here!</a> </div> The content within the div is dynamically loaded via ...

Alter the color as the text moves beneath a see-through layer

Imagine a scenario where there is a page with text and on top of that, there is a transparent div that is smaller than the text area. Is it feasible to dynamically alter the color of the text that scrolls underneath the transparent div? Picture the trans ...

How can I reference MyClass.new as a method in Typescript?

Within my code, I have an array of objects and each object is structured like this: { id: 'string', name: 'string' } There's a class defined as follows: class User { constructor(obj: Record<string, string>) { Object.as ...