在 Node.js 中,可以轻松地导入和解析 JSON 数据。

1. 使用 fs 模块读取本地 JSON 文件

Node.js 内置的 fs 模块可以用来读取本地文件。以下代码演示了如何读取一个名为 'data.json' 的 JSON 文件,并将数据解析为 JavaScript 对象:

const fs = require('fs');

fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) throw err;
  const jsonData = JSON.parse(data);
  console.log(jsonData);
});

2. 使用 request 模块发送 HTTP 请求获取远程 JSON 数据

对于远程的 JSON 数据,可以使用第三方的 request 模块发送 HTTP 请求。以下代码演示了如何发送一个 GET 请求获取 'https://example.com/api/data' 的 JSON 数据,并将数据解析为 JavaScript 对象:

const request = require('request');

request('https://example.com/api/data', { json: true }, (err, res, data) => {
  if (err) throw err;
  console.log(data);
});

这两种方法都能帮助你在 Node.js 中轻松地导入和解析 JSON 数据,根据你的需求选择合适的方法即可。

Node.js 如何导入和解析 JSON 数据

原文地址: https://www.cveoy.top/t/topic/obcE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录