Tips for saving JSON information into a variable using JavaScript

I am in need of a function called ** getJson () ** that can fetch and return data from a json file.

Here is the JSON data (file.json):

    [
        {
                "01/01/2021":"Confraternização Universal",
                "15/02/2021":"Carnaval",
                "16/02/2021":"Carnaval",
                "02/04/2021":"Paixão de Cristo",
                "21/04/2021":"Tiradentes",
                "01/05/2021":"Dia do Trabalho",
                "03/06/2021":"Corpus Christi",
                "07/09/2021":"Independência do Brasil",
                "12/10/2021":"Nossa Sr.a Aparecida - Padroeira do Brasil",
                "02/11/2021":"Finados",
                "15/11/2021":"Proclamação da República",
                "25/12/2021":"Natal"
        }
]
  1. I have attempted to use an async function, but it did not work as expected.

The code I used is:

async function getJson() {
    const response = await fetch('file.json');
    const data = await response.json();
    return data;
}
console.log(getJson());

Result:

Promise {<pending>}
  1. It would be beneficial if the fetched data could be stored in a variable like ** obj **. I tried the following code, but encountered a problem.

The code I tried is:

var obj;
async function getJson() {
    const response = await fetch('file.json');
    obj = await response.json();
}
console.log(obj);

Result:

undefinded

Answer №1

An Asynchronous function always results in a Promise. To retrieve the data, utilize the .then() method as demonstrated below:)

getJson().then(data=>console.log(data);

The following function is declared as async, guaranteeing that it returns a promise. If you attempt to console.log(getJson()), a resolved promise will be returned. To access the value from the resolved promise, we must use the .then() method with a callback containing the data.

async function getJson() {
    const response = await fetch('file.json');
    const data = await response.json();
    return data;
}
getJson().then(data=>console.log(data));

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

Handling errors in Angular and rxjs when encountering undefined returns in find operations

I am currently faced with the challenge of catching an error when the variable selectionId, derived from my route, is null or contains an invalid value. My code structure has a mechanism in place to handle errors when the category variable is undefined, bu ...

In nextjs, the page scroll feature stops functioning properly following a redirection

Currently, I am running on version 13.5.4 of Next.js In a server-side component, I am using the nextjs redirect function to navigate to another page. However, after the redirection, I noticed that the next page is missing the scroll bar and seems to be st ...

The repeated execution of a Switch Statement

Once again, I find myself facing a puzzling problem... Despite making progress in my game, revisiting one aspect reveals a quirk. There's a check to verify if the player possesses potions, and if so, attempts to use it involves calculating whether the ...

Having difficulty inputting password for telnet login using Node.js

When I use telnet from the Windows command line, everything works smoothly: > telnet telehack.com (... wait until a '.' appears) . login username? example password? (examplepass) * * * * * * * Logged... (...) @ (This is the prompt when you ...

What is the method for defining the maximum stack size in a node.js environment?

I encountered an error when trying to convert a docx file to epub format. Despite increasing the stack size, the task was unsuccessful. The specific error message I received is as follows: RangeError: Maximum call stack size exceeded at Array.filter (n ...

javascript authorization for iframes

I am currently working on a localhost webpage (parent) that includes an iframe displaying content from another url (child; part of a different webapp also on localhost). My goal is to use JavaScript on the parent-page to inspect the contents of the iframe ...

Setting the parent's height to match one of its children

I'm struggling to align the height of the pink '#images-wrap' with the main image. When there are too many small rollover images on the right, it causes the pink div to extend beyond the main image's height. If I could make them match i ...

Anticipating the completion of multiple observable subscription functions

Is there a way to replace and convert all words in an array using an object's method that returns an observable? I found a helpful solution on this post which uses bind to pass the correct value. After all subscriptions are complete, I want to execut ...

What could be causing my Javascript prompts to not appear in my Express.IO .ejs file?

I am fairly new to JavaScript and exploring Node with Express.IO. I'm currently working on a project that involves tracking real-time connections made by different 'users' to the server. However, I've encountered an issue where my promp ...

What could be the reason for the jQuery not displaying JSON data in the console log?

When I put this code into a file named test.html: <html> <head> <title>Test</title> </head> <body> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"& ...

Generate a fresh row in a table with user inputs and save the input values when the "save" button is

HTML: <tbody> <tr id="hiddenRow"> <td> <button id="saveBtn" class="btn btn-success btn-xs">save</button> </td> <td id="firstName"> <input id="first" type="tex ...

Is the memory efficiency of Object.keys().forEach() in JavaScript lower compared to a basic for...in loop?

Picture a scenario where you have an extremely large JS object filled with millions of key/value pairs, and your task is to loop through each of them. Check out this jsPerf example that demonstrates the different techniques for accomplishing this, highlig ...

Is it possible to use jQuery to load content and notify the calling window?

I am implementing the JQuery event "load" to detect when the full HTML window has finished loading along with all scripts being executed. I know this function is typically used within the document.ready event. However, my scenario involves a parent window ...

Using the hash(#) symbol in Vue 3 for routing

Even though I am using createWebHistory, my URL still contains a hash symbol like localhost/#/projects. Am I overlooking something in my code? How can I get rid of the # symbol? router const routes: Array<RouteRecordRaw> = [ { path: " ...

Independent Dropbox Collections

Query: function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for (var i = 0; i < colCount; i++) { var ...

Ways to verify whether a vue instance is empty within a .vue file by utilizing the v-if directive

I am facing an issue with a for-loop in Vue that iterates through a media object using v-for to check if it contains any images. Everything is working correctly, but I want to display a div below the loop saying "There is no media" when the object is empty ...

Dynamic Interactive Content with AJAX

Imagine if all the forms in your application followed this structure: <div id="result_messages"></div> <form action="/action"> <!-- all the form --> </form> Here's an example of what a submit button for this form might ...

Discover the magic of triggering events that dynamically alter CSS styles

I am trying to implement an eventBus in the App.vue component that allows me to change a modal's CSS based on a payload object. For example, if I pass { type: 'success' }, the border of the modal should turn green, and if I pass { type: &apo ...

sending numerous ajax requests and they all seem to be returning identical results

When firing multiple ajax requests using the setinterval() function, I noticed that both requests are bringing back the same information from another page. Here is the JavaScript code: function views() { setInterval(function(){var xmllhttp //alert ...

What is the best way to use Jquery to enclose a portion of a paragraph text within a

How can I wrap the content inside a span that comes after another span, inside a paragraph and a new span? To further illustrate this, consider the following example: <p>foo <span>bar</span> baz</p> The desired outcome is: <p& ...