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
Patricia ArquetteOriginal
2024-12-10 10:25:14724browse

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:

  1. Get the JSON data:

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

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

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

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

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!

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