JavaScript Lessons

JavaScript Read JSON File: Fetch and Parse Data

Learn how to read JSON data in JavaScript using fetch and res.json(). This lesson walks you through loading a JSON file and accessing its values with clear examples.

Serhat ALPASLAN2 min read

To read JSON (JavaScript Object Notation) data with JavaScript code, you can start by using the “JSON.parse()” method. This method converts a JSON text string into a JavaScript object. For example, the code block below takes a JSON text string and converts it into a JavaScript object with the “JSON.parse()” method:

 

var jsonData = '{"name":"John", "age":30, "city":"New York"}';
var jsObject = JSON.parse(jsonData);
console.log(jsObject.name); // "John"

You can also use the “eval()” method to do the same thing, but since “eval()” is a security risk, using “JSON.parse()” is recommended.

In addition, you can use JavaScript functions such as “fetch()” or “XMLHttpRequest” to read JSON data. For example, the code block below uses the “fetch()” method to read the data in a JSON file:

 

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

In this example, “fetch(‘data.json’)” sends a request to the “data.json” file. “response.json()” parses the incoming response as JSON, and “console.log(data)” prints it to the console.

Finally, the “jQuery” library is another option you can use to read JSON data. For example, the code block below uses the “jQuery.getJSON()” method to read the data in a JSON file:

 

$.getJSON("data.json", function(json) {
    console.log(json);
});

That’s how you can read JSON data with JavaScript. Pick whichever of these methods suits you best, and you can easily read your JSON data.

Share it if it helped

Write a comment