Home > Web Front-end > JS Tutorial > How Can I Read and Parse a Local JSON File in JavaScript?

How Can I Read and Parse a Local JSON File in JavaScript?

Patricia Arquette
Release: 2024-12-10 10:25:14
Original
731 people have browsed it

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"]
}
Copy after login

Code Solution

To read this JSON file and print its data in JavaScript, you can use the following steps:

  1. Get the JSON data:

    const fs = require('fs');
    const data = fs.readFileSync('test.json');
    Copy after login
  2. Parse the JSON data:

    const json = JSON.parse(data);
    Copy after login
  3. Access the data:

    console.log(`Resource: ${json.resource}`);
    console.log(`Literals: ${json.literals}`);
    Copy after login

Additional Considerations

  • The fs module in Node.js is used to read the file system.
  • Make sure the path to the JSON file is correct.
  • Handle errors gracefully if the file is not found or cannot be parsed.

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}`);
Copy after login

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!

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