Read local json file javascript

How to Read a JSON File in JavaScript – Reading JSON in JS

Joel Olawanle

Joel Olawanle

How to Read a JSON File in JavaScript – Reading JSON in JS

When fetching data from external sources or servers, you need to make sure that the data returned is in JSON format. Then you can consume the data within your application.

In some situations, when you’re working locally or when you upload the data file to a server, we might want to read these JSON data from a file.

We’ll learn how to do that in this tutorial.

How to Read a JSON File in JavaScript with the Fetch API

One standard method we can use to read a JSON file (either a local file or one uploaded to a server) is with the Fetch API. It uses the same syntax for both. The only difference would be the URL.

For example, suppose we have a local file within our project’s folder named data.json that contains the following JSON data:

We can now read this file in JavaScript using the Fetch API method:

 fetch('./data.json') .then((response) => response.json()) .then((json) => console.log(json)); 

In the above, we have been able to read a local JSON file. But unfortunately, when we run this in a browser, we might get the following CORS error because our file is not on a server:

s_9630F87AB23B79DCD31DCDD0E14D2C6C4A3007934D2E561803A41CF5C1FE0085_1659464623693_image

To fix this, we will make sure our JSON file is on a local or remote server. If we use the Live server on our IDE, we won’t get this error. But when we load our file directly, we will get this error.

As I said earlier, suppose we have this JSON file on a remote server and are trying to read this file in JavaScript. The same syntax will work:

 fetch('https://server.com/data.json') .then((response) => response.json()) .then((json) => console.log(json)); 

The fetch API is the preferable method to use when we want to read a JSON file either from an external server or local file into our JavaScript file.

How to Read a JSON file in JavaScript with the Import Statement

Another method we can use aside from making an HTTP request is the import statement. This method has a few complications, but we will address them all.

Just like in the previous section, suppose we have our JSON file that holds user data, such as user.json :

We can read this JSON data in JavaScript using the import statement this way:

 import data from './data.json'; console.log(data); 

Unfortunately, this will throw an error saying we cannot use the import statement outside a module. This is a standard error when we try to use the import statement in a regular JavaScript file, especially for developers who are new to JavaScript.

To fix this, we can add the type=»module» script tag in our HTML file where we referenced the JavaScript file, like this:

When we do this, we’ll still get another error:

s_9630F87AB23B79DCD31DCDD0E14D2C6C4A3007934D2E561803A41CF5C1FE0085_1659465574774_image

To fix this error, we need to add the file type of JSON to the import statement, and then we’ll be able to read our JSON file in JavaScript:

import data from './data.json' assert < type: 'json' >; console.log(data); 

This works perfectly as long as we run our files on a local or remote server. But suppose we run this locally – then we would get the CORS error.

s_9630F87AB23B79DCD31DCDD0E14D2C6C4A3007934D2E561803A41CF5C1FE0085_1659464623693_image

Wrapping Up

In this article, we have learned how to read a JSON file in JavaScript and the possible errors we might encounter when using each method.

It’s best to use the fetch API method when you want to make an HTTP request. For example, suppose we are fetching data from a mock JSON file which we will eventually pull from an API.

Still, in a situation where we don’t need to use an HTTP request, we could use the import statement. We can use the import statement when we use a library like React, Vue, and so on which has to do with modules. This means we won’t need to add the type of module, and also, we won’t need to add the type of file.

Neither method requires you to install a package or use a library as they are inbuilt. Choosing which method to use is totally up to you.

But a quick tip that differentiates these methods is that the Fetch API reads a JSON file in JavaScript by sending an HTTP request, while the import statement does not require any HTTP request but rather works like every other import we make.

Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.

Источник

How to Read a Local/Remote JSON File in JavaScript [Examples]

JavaScript Read JSON File

This article will show you how to read a JSON file into JavaScript as a JSON object – both local and remote files.

What is JSON?

JSON (JavaScript Object Notation) is a file format that stores objects, and arrays of objects, as human-readable text. It’s become the most popular method of storing and transmitting structured data on the internet.

Thousands of APIs (used for mapping, communication, authentication, and many other purposes) use it as the format for submitting and receiving data. Desktop applications also use it to store user data, and databases have adopted it for storing structured data.

It’s everywhere, so you’ll be getting pretty familiar with it no matter what you’re working on. Here’s how it looks:

Above, a list of pets is defined in JSON syntax. If you’ve been working with JavaScript objects, you’ll recognize that it is very similar to the syntax used to define objects and arrays in JavaScript. You can find out more about the JSON syntax itself here.

Parsing JSON in JavaScript

JSON is just text – it needs to be interpreted and converted into objects to be useful in JavaScript.

All of the below methods will do this and return usable objects and arrays as JavaScript objects.

Reading a File at URL from the Browser

If you are building a website and wish to read a JSON file using JavaScript being executed in the browser, it must be read from a URL – even if it’s stored on the same disk, in the same folder, as the JavaScript file being executed.

The fetch function in JavaScript will read the contents of a file at a given URL and has built-in functionality for parsing the JSON into usable JavaScript objects.

var url = 'https://example.com/test.json'; fetch(url) .then(response => response.json()) .then(json => < console.log(json); // Do stuff with the contents of the JSON file here >);

Above, fetch is used to retrieve the file at the given URL. The first then statement retrieves the JSON parsed version of the response.

The second then statement then contains the parsed JSON file ready for use – in this case, it’s simply logged to the console for inspection.

Reading a Local File from the Browser

The FileReader object, a relatively recent addition to HTML5 and JavaScript, allows you to read files stored locally on your computer directly into JavaScript running in a browser, without the need to first upload it to a server.

Note, the below example relies heavily on JavaScript Promises – so it’s worth getting familiar with them!

  

Reading a Local File from Node.js

The fs library in Node.js handles all local file read/write operations. Once it’s been used to read a file, the contents can simply be parsed into JSON:

const fs = require('fs'); let fileText = fs.readFileSync('data.json'); let jsonParsed = JSON.parse(fileText); console.log(jsonParsed);

Reading a Remote file from Node.js

The fetch method outlined above is also the best way to accomplish this from a Node.js environment – give it a shot!

Источник

3 Ways To Read JSON In JavaScript

A big part of data transactions between client and server is JSON. In this article, we will discuss 3 different ways to read JSON file in JavaScript.

read JSON file in javascript

JSON is used to store data in a structured way. You can store the data of your customer in a JSON file and then read it in JavaScript.

A JSON file can be stored in a server or in a client. We will see how to read them both.

1. Using fetch() method

The fetch() method is used to send and receive data from a server. It can be used to read JSON files stored in a server or in the client.

It is a core part of JavaScript and you do not need to import any library to use it.

Here, url is the URL of the JSON file. It can be a local file or a remote file.

The fetch() method returns a Promise object which is used to get the response from the server.

Here is a working example:

// read local JSON file in javascript fetch("./lib/examples/employee.json") .then(function (response) < return response.json(); >) .then(function (data) < console.log(data); >)

Press the run button and you will see that the JSON file is fetched and displayed in the console.

If your JSON file is in a remote server then you can follow the same steps just pass the correct URL of the JSON file in the fetch() method.

// read remote JSON file in javascript fetch("https://jsonplaceholder.typicode.com/users") .then(function (response) < return response.json(); >) .then(function (data) < for (let i = 0; i < data.length; i++) < console.log(data[i]); >>)

The above example will fetch the data from the remote server and display it in the console.

2. Using AJAX

AJAX is used to send and receive data from a server. You can use it to request a JSON file from a server and the server will send the data of the JSON file back to the client.

Note : AJAX supports http protocol only. It will not work for local files. To get the local files you need to run a server locally and you will be able to access local files.

Let’s see how to use AJAX to read JSON files in JavaScript.

// reading JSON file using AJAX // create a new XMLHttpRequest object var xhr = new XMLHttpRequest(); // open a connection xhr.open("GET", "./lib/examples/employee.json", true); // send the request xhr.send(); // handle the response xhr.onreadystatechange = function () < if (this.readyState == 4 && this.status == 200) < console.log(this.responseText); >>
  1. Create a new XMLHttpRequest object. This is the object that will be used to send and receive data from the server.
  2. Open a connection. Use the open() method to open a connection. The first parameter is the request type (GET or POST). The second parameter is the URL of the file (JSON here). The third parameter is true or false. If true then the request will be asynchronous otherwise it will be synchronous.
  3. Send the request. Use send() method to send the request.
  4. Handle the response. Use onreadystatechange event to handle the response. The onreadystatechange event is triggered when the readyState changes. The readyState is a number and it can be one of the following values:
    • 0 : request not initialized
    • 1 : server connection established
    • 2 : request received
    • 3 : processing request
    • 4 : request finished and response is ready

3. Using jQuery

jQuery is a JavaScript library that is used to make JavaScript easier to use. It provides many useful methods to make your life easier.

To get JSON you can use the $.getJSON() method which uses AJAX behind the scenes to get the JSON file from the server.

Since it uses AJAX, it will not work for local files.

Here is a working example of $.getJSON() method:

// read local JSON file using jQuery $.getJSON("./lib/examples/employee.json", function (data) < console.log(data); >)

Conclusion

We have seen 3 different ways to read JSON file in JavaScript. You can use the same method to read XML files as well and do something useful.

Источник

Читайте также:  How to create javascript html
Оцените статью