Home >Web Front-end >JS Tutorial >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:
{ "resource": "A", "literals": ["B", "C", "D"] }
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}`); } };
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>
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!