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

The functionality for tabbed content seems to be malfunctioning on Chrome and Firefox, however it works perfectly

In my index.js file, I have various functions set up like so: // a and b is placed at index.jsp $("#a").click(function (){ //this works on index.jsp and display.jsp(where the servlets forwards it). $("#b").load('servletA.html?action=dis ...

Please make sure to utilize messageCreate instead of the deprecated message event

Hey there, I'm currently in the process of upgrading my discord bot from v12 to v13. The bot is up and running, all commands are loaded in the console, but I'm facing an issue where a notification keeps popping up at the bottom and none of my com ...

Unsynchronized state of affairs in the context of Angular navigation

Within my Angular project, I am currently relying on an asynchronous function called foo(): Promise<boolean>. Depending on the result of this function, I need to decide whether to display component Foo or Bar. Considering my specific need, what woul ...

Using Python to transform a requests response into a Pandas DataFrame after converting it to JSON

I am utilizing the requests module to receive a response in JSON format similar to the image provided in the link below. My attempt to convert this response into a dataframe has resulted in columns like "currentPage", "data", "message", etc. However, I ne ...

Incorporating descriptions below the images within this JavaScript carousel

I'm struggling to add text under the images in this slider. The functionality is simple, but I can't figure it out. I might have to rewrite it. Here's the HTML and JS: <div id="look-book-scroll"> <a href="javascript:;" id="lookbo ...

Guide to making a 'Put' request using a JSON object towards a JSONPlaceHolder RESTful API in Java

I have a piece of code that retrieves all the data from the JSONPlaceHolder REST API and converts it into an array. Afterwards, I collect input from text fields in my program to create a JSON Object with that information. Now, I want to send this JSON Obje ...

Is it possible to utilize ember-cli solely as a frontend tool, much like how we use JavaScript and jQuery?

Is it feasible to employ ember-cli exclusively as a front-end tool, similar to utilizing JavaScript and jQuery? I am interested in incorporating a reference to ember-cli in my .NET project solely for validation purposes. Is this a viable approach, and an ...

Is there a way to automatically trigger a function once another function has completed its execution?

I am diving into the world of JavaScript as a beginner. All I want to do is trigger the function called seconOne() right after the execution of firstOne(). Specifically, I need the function two to be invoked when the value of p1 reaches 4. While I can us ...

modifying Redux state according to the position in an array

In my food truck app, I have stored customer orders in the redux state as an array of objects. Each order includes a list of items selected by the customer, along with the count, name, and total price for each item. For example: state.order = [ {item: " ...

React Highchart issue: The synchronized chart and tooltip are failing to highlight the data points

I am currently utilizing the highchart-react-official library to create two types of charts: 1) Line chart with multiple series 2) Column Chart. My objective is to implement a synchronized behavior where hovering over a point in the first line chart hig ...

I am experiencing an issue where my JSON array is only returning the last element. Any suggestions on how to

I am facing an issue with my JSON array and Ajax code. Here is the snippet of my code where I upload an Excel file, convert it to JSON, then save it as a string in my database: function exportExcelToTable() { $('#upload-excel-convert').chang ...

jQuery load() function triggers unexpected error in jQuery plugin

Here is the current structure of my page: <body> <div id="menuBar"> </div> <canvas id="myCanvas" width="700" height="700" style="border:1px solid #000000;"></canvas> </body> <script src="../Scripts/jQuery.mazeBo ...

The file module.js is encountering an error at line 327 because it is unable to locate the module named 'express

Hey there, I'm new to nodejs and whenever I run a file in the command prompt like:- C:\demoData>node demo.js I encounter an error like this: module.js:327 throw err; ^ Error: Cannot find module 'express' at Function.M ...

Accurate linking to the interface while retrieving information from a specified URL

Just started with Angular and attempting to assign the returned json data to my interface, but it's not working as expected. Check out the code I'm using below: Stackblitz Json URL ...

Guide on incorporating an Angular directive to substitute an element under specific conditions

My goal is to create a directive that replaces an anchor element with a div element under certain conditions. The content of the anchor element should remain unchanged and be included within the new element. The concept involves having an attribute on the ...

style the table cells based on results of winner values retrieved from JSON

After fetching JSON data, I am utilizing angular JS to present it in a table. The table consists of multiple rows that are populated from the JSON file using ng-repeat. The value for Status.winner can either be 0 or 1. If the winner's value for a p ...

What is the best way to conditionally wrap a useState variable in an if statement without losing its value when accessing it outside the if block in reactjs?

I am facing a coding challenge with my cards state variable in React using the useState hook. I tried adding my array data to it but ended up with an empty array. Placing the state inside an if statement resulted in undefined variables. I attempted various ...

Simulated function invocation just one time

I am testing the functionality of two functions in the same file. One of the functions is supposed to call the other, and I need to verify that this interaction occurs. import * as strings from './strings'; const generateUuidSpy = jest.spyOn(st ...

Having trouble with implementing Nested routes in Vuejs?

main.js import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import HelloWorld from "./components/HelloWorld"; import User from " ...

Is there a way for me to compare a string A1 with a value A2 located in index 0 within an array of values?

In my current task, I am attempting to compare two sets of strings: A1 must match A2 when selected. However, if A1 is chosen along with B1, C1, or D1, the comparison should return false. Similarly, selecting B1 should result in a match with only B2, while ...