Home >Web Front-end >JS Tutorial >How Can I Read and Parse a Local JSON File in JavaScript?
Reading External Local JSON Files in JavaScript
In web development, it's often necessary to access local data stored in JSON files. With JavaScript, this can be achieved by leveraging the JSON.parse() method.
Problem Statement
You have a local JSON file named "test.json" stored at /Users/Documents/workspace/test.json. The file contains the following JSON data:
{ "resource": "A", "literals": ["B", "C", "D"] }
Code Solution
To read this JSON file and print its data in JavaScript, you can use the following steps:
Get the JSON data:
const fs = require('fs'); const data = fs.readFileSync('test.json');
Parse the JSON data:
const json = JSON.parse(data);
Access the data:
console.log(`Resource: ${json.resource}`); console.log(`Literals: ${json.literals}`);
Additional Considerations
Example Code
const fs = require('fs'); // Read the JSON file const data = fs.readFileSync('test.json'); // Parse the JSON data const json = JSON.parse(data); // Access the data console.log(`Resource: ${json.resource}`); console.log(`Literals: ${json.literals}`);
The above is the detailed content of How Can I Read and Parse a Local JSON File in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!