Home >Web Front-end >JS Tutorial >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"] }
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); } });
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
This should output:
A B C D
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!