How to Read a Json File in Javascript

Load JSON File in JavaScript

  1. Employ the require() Function to Load JSON Files in JavaScript
  2. Use the fetch() Function to Load JSON Files in JavaScript

JSON stands for JavaScript Object Notion. It is used for sharing data between servers and clients. JavaScript allows us to load local JSON.

We volition discuss how to load JSON files in this commodity.

We will read the following JSON file.

              "Students" : [    {       "firstName":"Ram","lastName":"Sharma"    }  ] }                          

Use the require() Function to Load JSON Files in JavaScript

In JavaScript, we can use the crave() method to load files and modules. This takes the path of the local file where it has been saved. With the help of the console.log() function, it loads the information in the server and displays it.

For instance,

              const jsonData= crave('./students.json');  panel.log(jsonData);                          

Output:

              "Students" : [    {       "firstName":"Ram","lastName":"Sharma"    }  ] }                          

Use the fetch() Function to Load JSON Files in JavaScript

This function fetches the file from the path where information technology is saved and and so returns the file as the response in the console.data. This function is only suitable for working in the web-based environment every bit the fetch API works only in that surround.

After reading the file, we parse the data using json() role and display information technology.

The below code demonstrates the above part.

              fetch("./students.json") .and so(response => {    render response.json(); }) .and then(jsondata => console.log(jsondata));                          

Output:

              "Students" : [    {       "firstName":"Ram","lastName":"Sharma"    }  ] }                          

Write for us

DelftStack articles are written past software geeks similar you lot. If you besides would like to contribute to DelftStack by writing paid manufactures, you can check the write for us page.

Related Commodity - JavaScript JSON

  • JavaScript Pretty Print JSON
  • Convert JSON to Object in JavaScript
  • Ezoic

    alvaradothosollover.blogspot.com

    Source: https://www.delftstack.com/howto/javascript/load-json-file-in-javascript/

    0 Response to "How to Read a Json File in Javascript"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel