Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 读取json文件

作者:寂寞带点伤   发布日期:2025-02-25   浏览:71

// 读取 JSON 文件的示例代码

// 假设我们有一个名为 'data.json' 的文件,内容如下:
/*
{
  "name": "Alice",
  "age": 25,
  "city": "New York"
}
*/

// 方法1: 使用 Node.js 的 fs 模块同步读取 JSON 文件
const fs = require('fs');

try {
  // 读取文件内容
  const data = fs.readFileSync('data.json', 'utf8');

  // 将字符串解析为 JavaScript 对象
  const jsonData = JSON.parse(data);

  console.log(jsonData); // 输出: { name: 'Alice', age: 25, city: 'New York' }
} catch (err) {
  console.error('Error reading or parsing the JSON file:', err);
}

// 方法2: 使用 Node.js 的 fs 模块异步读取 JSON 文件
fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the JSON file:', err);
    return;
  }

  try {
    // 将字符串解析为 JavaScript 对象
    const jsonData = JSON.parse(data);

    console.log(jsonData); // 输出: { name: 'Alice', age: 25, city: 'New York' }
  } catch (parseErr) {
    console.error('Error parsing the JSON file:', parseErr);
  }
});

// 方法3: 在浏览器环境中使用 Fetch API 读取 JSON 文件
fetch('data.json')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // 自动解析 JSON 响应
  })
  .then(jsonData => {
    console.log(jsonData); // 输出: { name: 'Alice', age: 25, city: 'New York' }
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

解释说明:

  1. 方法1:使用 Node.js 的 fs.readFileSync 方法同步读取 JSON 文件。该方法会阻塞代码执行,直到文件读取完成。适合用于简单的脚本或初始化阶段。

  2. 方法2:使用 Node.js 的 fs.readFile 方法异步读取 JSON 文件。该方法不会阻塞代码执行,适合用于生产环境中的文件读取。

  3. 方法3:在浏览器环境中使用 fetch API 读取 JSON 文件。fetch 是现代浏览器中常用的网络请求工具,支持 Promise,可以方便地处理异步操作并自动解析 JSON 响应。

以上三种方法分别适用于不同的环境和需求。

上一篇:js 生成数组

下一篇:js 字符串数组排序

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 获取今天年月日

js jsonp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站