Request 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.

Читайте также:  Python selenium find element by title

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.

Источник

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.

Читайте также:  Css убрать синее выделение при клике

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
Читайте также:  text-align

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.

Источник

JSON Http Request

A common use of JSON is to read data from a web server, and display the data in a web page.

This chapter will teach you, in 4 easy steps, how to read JSON data, using XMLHttp.

JSON Example

This example reads a menu from myTutorials.txt, and displays the menu in a web page:

JSON Example

var xmlhttp = new XMLHttpRequest();
var url = «myTutorials.txt»;

Example Explained

1: Create an array of objects.

Use an array literal to declare an array of objects.

Give each object two properties: display and url.

Name the array myArray:

myArray

var myArray = [
«display»: «JavaScript Tutorial»,
«url»: «https://www.w3schools.com/js/default.asp»
>,
«display»: «HTML Tutorial»,
«url»: «https://www.w3schools.com/html/default.asp»
>,
«display»: «CSS Tutorial»,
«url»: «https://www.w3schools.com/css/default.asp»
>
]

2: Create a JavaScript function to display the array.

Create a function myFunction() that loops the array objects, and display the content as HTML links:

myFunction()

Call myFunction() with myArray as argument:

Example

3: Create a text file

Put the array literal in a file named myTutorials.txt:

myTutorials.txt

[
«display»: «JavaScript Tutorial»,
«url»: «https://www.w3schools.com/js/default.asp»
>,
«display»: «HTML Tutorial»,
«url»: «https://www.w3schools.com/html/default.asp»
>,
«display»: «CSS Tutorial»,
«url»: «https://www.w3schools.com/css/default.asp»
>
]

4: Read the text file with an XMLHttpRequest

Write an XMLHttpRequest to read the text file, and use myFunction() to display the array:

XMLHttpRequest

var xmlhttp = new XMLHttpRequest();
var url = «myTutorials.txt»;

xmlhttp.open(«GET», url, true);
xmlhttp.send();

Источник

Оцените статью