Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP W3.CSS C C++ C# HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

JS Tutorial

JS Home JS Introduction JS Where To JS Output JS Syntax JS Operators JS If Conditions JS Loops JS Strings JS Numbers JS Functions JS Timers JS Objects JS Scope JS Dates JS Temporal  New JS Arrays JS Sets JS Maps JS Iterations JS Math JS RegExp JS Data Types JS Errors JS Debugging JS Style Guide JS Reference JS Projects  New JS Versions JS HTML DOM JS HTML Events JS HTML First

JS Advanced

JS Functions JS Objects JS Classes JS JSON JS Asynchronous JS Modules JS Meta & Proxy JS Typed Arrays JS DOM Navigation JS Browser API JS Web API JS Graphics

Old Technologies

JS AJAX JS jQuery JS JSONP

JS Examples

JS Examples

JavaScript Loading JSON

JSON is often stored in files or returned by web servers.

JavaScript can load JSON and convert it into JavaScript values.

The modern way to load JSON is with the fetch() method.

This chapter assumes that you are familiar with fetch().

If not, see the JavaScript Fetch API tutorial.


A JSON File

JSON files normally use the .json extension.

customer.json

{
  "name": "John",
  "age": 30,
  "city": "New York"
}

Loading JSON

Use fetch() to request the JSON file.

The response.json() method parses the JSON and returns a JavaScript value.

Example

async function loadJSON() {
  const response = await fetch("customer.json");
  const customer = await response.json();

  document.getElementById("demo").innerHTML = customer.name;
}

loadJSON();

Loading a JSON Array

If the file contains a JSON array, response.json() returns a JavaScript array.

products.json

[
  {"name":"Laptop","price":899},
  {"name":"Mouse","price":29},
  {"name":"Keyboard","price":79}
]

Example

async function loadProducts() {
  const response = await fetch("products.json");
  const products = await response.json();

  document.getElementById("demo").innerHTML = products[0].name;
}

loadProducts();


Sending JSON

The fetch() method can also send JSON to a web server.

Use the POST method to send new data.

Convert the JavaScript object to JSON text with JSON.stringify().

Example

const person = {
  name: "John",
  age: 30
};

const response = await fetch("/api/person", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(person)
});

The Request Options

The second argument of fetch() contains the request options.

Option Description
method The HTTP request method, such as POST.
headers Additional information about the request.
body The data sent with the request.

The Content-Type Header

The Content-Type header tells the server what type of data is being sent.

Example

headers: {
  "Content-Type": "application/json"
}

The value application/json tells the server that the request body contains JSON.


The Request Body

The request body must contain text, not a JavaScript object.

Use JSON.stringify() to convert the object into JSON text.

Example

body: JSON.stringify(person)

JSON.stringify() converts a JavaScript value into JSON text.


Reading the Server Response

A server can return JSON after receiving the request.

Use response.json() to read the returned JSON.

Example

const person = {
  name: "John",
  age: 30
};

const response = await fetch("/api/person", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(person)
});

const result = await response.json();

document.getElementById("demo").textContent = result.message;

Checking the Response

The fetch() method does not reject its Promise for HTTP errors such as 404 or 500.

Check the response.ok property before reading the response.

Example

const response = await fetch("/api/person", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(person)
});

if (!response.ok) {
  throw new Error("HTTP error " + response.status);
}

const result = await response.json();

Sending JSON with Error Handling

Use try...catch to handle request and response errors.

Example

async function sendPerson() {
  const person = {
    name: "John",
    age: 30
  };

  try {
    const response = await fetch("/api/person", {
      method: "POST",
      headers: {
          "Content-Type": "application/json"
      },
      body: JSON.stringify(person)
    });

    if (!response.ok) {
      throw new Error("HTTP error " + response.status);
    }

    const result = await response.json();

    document.getElementById("demo").textContent =
    result.message;
  }
  catch (error) {
    document.getElementById("demo").textContent =
    error.message;
  }
}

sendPerson();

Complete Example

This example sends form data to a server as JSON.

Example

<input id="name" value="John">
<input id="age" type="number" value="30">
<button onclick="sendPerson()">Send</button>




Sending JSON Summary

  • Use fetch() to send JSON to a server.
  • Use method: "POST" to send new data.
  • Set Content-Type to application/json.
  • Use JSON.stringify() to create the request body.
  • Use response.json() to read a JSON response.
  • Check response.ok for HTTP errors.
  • Use try...catch to handle errors.

Checking for Errors

The fetch() method does not throw an error for HTTP errors such as 404.

Check the ok property before reading the JSON.

Example

async function loadJSON() {
  const response = await fetch("customer.json");

  if (!response.ok) {
    throw new Error("HTTP error " + response.status);
  }

  const customer = await response.json();

  document.getElementById("demo").innerHTML = customer.name;
}

loadJSON();

Handling Errors

Use try...catch to handle loading errors.

Example

async function loadJSON() {
  try {
    const response = await fetch("customer.json");

    if (!response.ok) {
      throw new Error("HTTP error " + response.status);
    }

    const customer = await response.json();

    document.getElementById("demo").innerHTML = customer.name;
  }
  catch(err) {
    document.getElementById("demo").innerHTML = err.message;
  }
}

loadJSON();

Loading JSON from a Server

The URL passed to fetch() can point to a JSON file or a web server.

Example

const response = await fetch("/api/customers");

const customers = await response.json();

It does not matter whether the JSON comes from a static file or is generated by a server.


What Does response.json() Return?

The response.json() method returns a Promise.

When the Promise is fulfilled, it provides the parsed JavaScript value.

The returned value can be:

  • A JavaScript object
  • A JavaScript array
  • A string
  • A number
  • A Boolean
  • null

Loading JSON Summary

  • Use fetch() to load JSON.
  • Use response.json() to parse the JSON.
  • response.json() returns a Promise.
  • Check response.ok for HTTP errors.
  • Use try...catch to handle errors.
  • JSON can come from files or web servers.

The response.json() method already parses the JSON.

Do not pass its result to JSON.parse().

The fetch() method does not reject its Promise for HTTP errors such as 404.

Always check response.ok.



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->