Open Playground
JS Web APIsLesson #186

JavaScript Loading JSON

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

The fetch() Method

JSON is often stored in files or returned by calls to 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

Example Code

javascript
Try it Yourself
{

  "id": 101,

  "name": "John Doe",

  "city": "New York",

  "member": true

}

Loading JSON

Use the fetch() method to request the JSON file.

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

Example

Example Code

javascript
Try it Yourself
async function loadJSON() {

  const response = await fetch("customer.json");

  const customer = await response.json();

  myDisplayer(customer.name);

}

loadJSON();

Loading a JSON Array

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

products.json

Example Code

javascript
Try it Yourself
[

  {"name":"Laptop","price":899},

  {"name":"Mouse","price":29},

  {"name":"Keyboard","price":79}

]

Example

Example Code

javascript
Try it Yourself
async function loadProducts() {

  const response = await fetch("products.json");

  const products = await response.json();

   myDisplayer(products[0].name);

   myDisplayer(products[0].price);

}

loadProducts();

Checking for Errors

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

Check the ok and status properties before reading the JSON file.

Example

Example Code

javascript
Try it Yourself
async function loadJSON(file) {

  const response = await fetch(file);

  myDisplayer(response.ok);

  myDisplayer(response.status);

  const customer = await response.json();

  myDisplayer(customer.name);

}

loadJSON("customer.json");

Handling Errors

Use try...catch to handle loading errors.

Example

Example Code

javascript
Try it Yourself
async function loadJSON(file) {

  try {

    const response = await fetch(file);

    if (!response.ok) {

      throw new Error("HTTP error " + response.status);

    }

    const customer = await response.json();

    myDisplayer(customer.name);

  }

  catch(err) {myDisplayer(err.message)}

}

loadJSON("customer.json");

Loading Multiple JSON Files

Independent downloads can run in parallel.

Example

Example Code

javascript
Try it Yourself
// Async function to download files

async function loadData() {

  const [customerResponse, productsResponse, newsResponse] = await Promise.all([

    fetch("customer.json"),

    fetch("products.json"),

    fetch("news.json")

  ]);

  const customer = await customerResponse.json();

  const products = await productsResponse.json();

  const news = await newsResponse.json();

  myDisplayer("Custome name: " + customer.name);

  myDisplayer(products.length + " products");

  myDisplayer(news.length + " news items");

}

// Call the async function

loadData();

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

Example Code

javascript
Try it Yourself
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.

OptionDescription
methodThe HTTP request method, such as POST.
headersAdditional information about the request.
bodyThe data sent with the request.

The Content-Type Header

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

Example

Example Code

javascript
Try it Yourself
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

Example Code

javascript
Try it Yourself
body: JSON.stringify(person)

Reading the Server Response

A server can return JSON after receiving the request.

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

Example

Example Code

javascript
Try it Yourself
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

Example Code

javascript
Try it Yourself
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

Example Code

javascript
Try it Yourself
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

Example Code

html
Try it Yourself
Send

async function sendPerson() {

  const person = {

    name: document.getElementById("name").value,

    age: Number(document.getElementById("age").value)

  };

  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;

  }

}

Interactive Code Examples

customer.json

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
{

  "id": 101,

  "name": "John Doe",

  "city": "New York",

  "member": true

}

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
async function loadJSON() {


  const response = await fetch("customer.json");


  const customer = await response.json();



  myDisplayer(customer.name);


}



loadJSON();

products.json

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
[

  {"name":"Laptop","price":899},

  {"name":"Mouse","price":29},

  {"name":"Keyboard","price":79}

]

JS Example 4

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
async function loadProducts() {


  const response = await fetch("products.json");


  const products = await response.json();



   myDisplayer(products[0].name);

   myDisplayer(products[0].price);


}



loadProducts();

JS Example 5

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
async function loadJSON(file) {

  const response = await fetch(file);

  myDisplayer(response.ok);

  myDisplayer(response.status);



  const customer = await response.json();

  myDisplayer(customer.name);


}



loadJSON("customer.json");

JS Example 6

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
async function loadJSON(file) {

  try {

    const response = await fetch(file);

    if (!response.ok) {

      throw new Error("HTTP error " + response.status);

    }

    const customer = await response.json();

    myDisplayer(customer.name);

  }

  catch(err) {myDisplayer(err.message)}

}



loadJSON("customer.json");