Home > Web Front-end > JS Tutorial > How Can I Read Data from a Local JSON File Using JavaScript?

How Can I Read Data from a Local JSON File Using JavaScript?

Barbara Streisand
Release: 2024-12-22 05:26:14
Original
632 people have browsed it

How Can I Read Data from a Local JSON File Using JavaScript?

Reading External Local JSON Files in JavaScript

To access data from an external local JSON file in JavaScript, follow these steps:

Create JSON File:

  • Save the JSON data in a local file, e.g., test.json with the following content:
{
  "resource": "A",
  "literals": ["B", "C", "D"]
}
Copy after login

JavaScript Code:

Once the JSON file is created, write a JavaScript script to read it:

// Step 1: Get JSON file path
const filePath = "/Users/Documents/workspace/test.json";

// Step 2: Create XMLHttpRequest object
const xhr = new XMLHttpRequest();

// Step 3: Open and send request
xhr.open("GET", filePath);
xhr.send();

// Step 4: Handle response
xhr.onload = function() {
  if (xhr.status === 200) {
    const response = JSON.parse(xhr.responseText);

    // Step 5: Access JSON data
    console.log(response.resource); // Output: "A"
    console.log(response.literals); // Output: ["B", "C", "D"]
  } else {
    console.error(`Error: ${xhr.status} - ${xhr.statusText}`);
  }
};
Copy after login

Example Usage:

To use this code, include both the test.json file and the JavaScript script in your HTML document:

<script src="/Users/Documents/workspace/test.json"></script>
<script src="script.js"></script>
Copy after login

This code establishes an asynchronous HTTP GET request to the JSON file, retrieves the response, parses it as JSON, and prints the relevant data to the console.

The above is the detailed content of How Can I Read Data from a Local JSON File Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template