Home >Web Front-end >JS Tutorial >How Can I Access External Local JSON Files in JavaScript?

How Can I Access External Local JSON Files in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-28 00:55:11695browse

How Can I Access External Local JSON Files in JavaScript?

Accessing External Local JSON Files in JavaScript

JSON (JavaScript Object Notation) is a popular format for data exchange, and it can be useful to read JSON data from external local files in JavaScript. Here's how you can do it:

  1. Fetch the JSON File's Data:
fetch("path/to/json.json")
  .then(response => response.json())
  .then(data => {
    // Use the JSON data as needed...
  })
  .catch(error => {
    // Handle any errors here...
  });
  1. Specify the JSON File Path:
const filePath = "/Users/Documents/workspace/test.json";

fetch(filePath)
  .then(response => response.json())
  .then(data => {
    // Print the JSON data
    console.log(data.resource);
    console.log(data.literals);
  })
  .catch(error => {
    // Handle any errors here...
  });

By following these steps, you can easily access external local JSON files in JavaScript and work with the data as needed.

The above is the detailed content of How Can I Access External Local JSON Files in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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