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

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

Susan Sarandon
Susan SarandonOriginal
2024-12-06 05:49:18230browse

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

Reading External Local JSON Files in JavaScript: Step-by-Step Guide

Suppose you want to access data stored in a local JSON file using JavaScript. Here's a comprehensive guide to solve your problem:

Prerequisites:

  • You have a JSON file named "test.json" saved on your local system.
  • The path to the file is "/Users/Documents/workspace/test.json".

Step-by-Step Code:

Create a data.json file with similar content like your sample JSON. Next, follow these steps in the JavaScript file:

  1. Import the JSON File:
<script type="text/javascript" src="data.json"></script>
  1. Retrieve the JSON Object:
var myData = JSON.parse(data);
  1. Access Data Properties:

To access individual data properties, use the following syntax:

alert(myData[0].name); // Outputs "Ashwin"
alert(myData[0].age); // Outputs "20"

Here's the complete JavaScript code:

<script type="text/javascript" src="data.json"></script>

By following these steps, you can efficiently read and access data from an external local JSON file using JavaScript.

The above is the detailed content of How Can I Read and Access Data from a Local JSON File Using 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