js读取json文件

1. 原生的两种方法

1.1 XMLHttpRequest

const xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/json");
xhr.open('GET', 'data.json', true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);
    // 对象中的属性可以像平常一样访问
    console.log(data);
  }
};
xhr.send(null);

1.2 使用浏览器原生的fetch API

fetch('data.json')
  .then(response => response.json())
  .then(data => {
    // 在这里可以操作读取到的 JSON 数据对象
    console.log(data);
  })
  .catch(error => {
    // 处理错误情况
    console.error('Error reading the JSON file:', error);
  });

2. 引入库的方法

2.1 Axios

<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js"></script>

axios.get('data.json')
  .then(response => {
    const data = response.data;
    // 对象中的属性可以像平常一样访问
    console.log(data);
  })
  .catch(error => {
    console.error('Error reading the JSON file:', error);
  });

2.2 jQuery中的getJSON

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

$.getJSON("data.json", function (data) {
   	console.log(data)
});

2.3 Node.js中的fs模块

const fs = require('fs');

fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the file:', err);
    return;
  }
  const jsonContent = JSON.parse(data);
  // 对象中的属性可以像平常一样访问
  console.log(jsonContent);
});

2.4 Vue项目

const data = require('@/data.json');
console.log(data);
console.log(data.salesTotal);

或者

import myData from '@/data.json'

console.log("myData", myData);
console.log("myData", myData.salesTotal);

3. 跨域问题

3.1 使用Live Server

在这里插入图片描述

3.2 在本地启动一个服务

给网页添加一个域名, 比如localhost, 我们可以使用python或者nodejs在本地启动一个服务, 这里以python3为例:

python -m http.server 8000

3.3 修改本地浏览器设置

修改本地浏览器设置, 以Windows平台谷歌浏览器为例, 启动时添加参数–allow-file-access-from-files
在这里插入图片描述

### 使用 JavaScript 读取和写入 JSON 文件 在浏览器环境中,由于安全原因无法直接访问本地文件系统来读写 JSON 文件。然而,在 Node.js 环境下可以轻松实现这一功能。 #### 一、Node.js读取 JSON 文件 为了从文件中加载 JSON 数据并将其解析为对象,可利用 `fs` 模块中的同步方法 `readFileSync()` 或者异步版本 `readFile()`. 下面是一个简单的例子展示如何完成此操作: ```javascript const fs = require('fs'); // 同步方式读取json文件 try { const dataBuffer = fs.readFileSync('data.json'); const jsonData = JSON.parse(dataBuffer.toString()); console.log(jsonData); } catch (err) { console.error(err.message); } ``` 对于更复杂的场景推荐采用回调函数处理错误以及数据流的方式来进行非阻塞式的 I/O 操作[^2]. #### 二、Node.js 中写入 JSON 文件 当需要保存 JavaScript 对象到磁盘上的 JSON 文件时,则应该先通过 `JSON.stringify()` 方法序列化该对象成字符串形式再调用 `writeFileSync()` 函数存储至目标位置: ```javascript const fs = require('fs'); let myObject = { name: 'Alice', age: 25 }; // 将js对象转换为json字符串 const jsonString = JSON.stringify(myObject); // 写入json文件 try { fs.writeFileSync('output.json', jsonString); console.log('成功写入文件'); } catch (err) { console.error(err.message); } ``` 同样地,在生产环境建议使用带有回调机制的 `writeFile()` 实现更好的性能表现.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值