Monday, January 20, 2025
HomeProgrammingHow To Read An External Local JSON File In JavaScript?

How To Read An External Local JSON File In JavaScript?

To read an external local JSON file in JavaScript, you can use various approaches depending on your environment (e.g., Node.js or browser). Below are solutions for both scenarios:

1. In a Web Browser (Client-Side JavaScript)

In a browser, you can use the fetch() API to load a JSON file from the local server or from the file system (with some limitations).

Example:

Assuming you have a JSON file named data.json in the same directory as your HTML file:

// data.json
{
  "name": "John",
  "age": 30,
  "city": "New York"
}

You can use fetch() to load and read the file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Read JSON Example</title>
</head>
<body>
  <h1>Read JSON Example</h1>
  <script>
    // Fetch the JSON file from the local server
    fetch('data.json')
      .then(response => response.json()) // Parse the JSON data
      .then(data => {
        console.log(data); // Log the data or use it in your application
        document.body.innerHTML += `<p>Name: ${data.name}, Age: ${data.age}, City: ${data.city}</p>`;
      })
      .catch(error => console.error('Error reading JSON:', error));
  </script>
</body>
</html>

Explanation:

  • The fetch('data.json') fetches the file data.json.
  • response.json() parses the JSON data into a JavaScript object.
  • You can then use this data in your application.
See also  Programmatically Stop Execution Of Python Script?

2. In Node.js (Server-Side JavaScript)

In a Node.js environment, you can use the fs module to read a local JSON file.

Example:

  1. Install Node.js if you haven’t already.
  2. Create a data.json file:
// data.json
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
  1. Use the following Node.js code to read and parse the JSON file:
const fs = require('fs');

// Read the JSON file
fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the file:', err);
    return;
  }
  // Parse the JSON data
  const parsedData = JSON.parse(data);
  console.log(parsedData);  // Log the parsed data

  // Access specific values
  console.log(`Name: ${parsedData.name}, Age: ${parsedData.age}, City: ${parsedData.city}`);
});

Explanation:

  • The fs.readFile() function reads the file asynchronously. The second argument ('utf8') specifies the character encoding.
  • The content of the file is passed to the callback, and JSON.parse() is used to parse the string into a JavaScript object.
  • You can then access the parsed data and work with it as needed.
See also  Sudo Command in Linux With Examples

3. Using XMLHttpRequest in the Browser (Old Method)

For older browsers that do not support fetch(), you can use the XMLHttpRequest method.

Example:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true); // Open the file
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const data = JSON.parse(xhr.responseText); // Parse the JSON
    console.log(data);  // Use the data
  }
};
xhr.send(); // Send the request

This method is largely replaced by fetch() but still works if you need compatibility with older browsers.

See also  How to Print lists in python

 

  • In the browser, use fetch() to read a local JSON file (served via a local server, like when running a development server).
  • In Node.js, use the fs module to read a JSON file from the local file system.
  • Old method: XMLHttpRequest can be used for older browser support.

If you’re working in a local environment and need the JSON file to be accessible, you may need to run a simple local server (e.g., using http-server in Node.js or Python’s http.server).

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x