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

How Can I Read External JSON Files in JavaScript?

Barbara Streisand
Release: 2024-12-08 04:55:13
Original
572 people have browsed it

How Can I Read External JSON Files in JavaScript?

Reading External JSON Files in JavaScript

This article provides a comprehensive guide on how to read an external local JSON file in JavaScript. The provided code sample incorporates both the JSON file and the JavaScript code to help you understand the process effectively.

Code Implementation:

1. Create a JSON File:

Save the following data into a file named test.json:

{
  "resource": "A",
  "literals": ["B", "C", "D"]
}
Copy after login

2. JavaScript Code:

// Get the path to the JSON file
const filePath = "/Users/Documents/workspace/test.json";

// Fetch the JSON file and store it in a variable
fetch(filePath)
  .then(response => response.json())
  .then(data => {
    // Print the resource
    console.log(data.resource);

    // Iterate and print the literals
    for (let literal of data.literals) {
      console.log(literal);
    }
  });
Copy after login

3. Executing the Code:

Assuming the JSON file and the JavaScript file are in the same folder, open a terminal window and navigate to that folder. Then, execute the following command:

node your_javascript_file.js
Copy after login

This should output:

A
B
C
D
Copy after login

The above is the detailed content of How Can I Read External JSON Files in 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