当前位置: 首页 > news >正文

Node.js JSON import attributes All In One

Node.js & JSON & import attributes All In One

你遇到的错误是因为 Node.js 对导入 JSON 的语法进行了调整:在较新的版本中,assert 关键字已被 with 关键字取代。这是由于 ECMAScript 标准的更新,将「导入断言」(import assertions)更名为「导入属性」(import attributes)。
解决方案:将 assert 替换为 with.

Node.js 18.17+ 或支持最新标准的环境中,正确的 JSON 导入语法应为:

// 导入 JSON 文件(使用新的 with 语法)
import carData from './data/car-prices.json' with { type: 'json' };

image

注意事项
Node.js 版本要求:
with 关键字语法需要 Node.js 18.17.0+ 或更高版本(LTS 版本推荐 20.x+)。
如果你使用的是较旧的 Node.js 版本(如 16.x 或 18.16 以下),可能不支持 with,此时建议使用 fs 模块读取(见下方兼容方案)。
ES 模块环境:
必须在 ES 模块环境中使用(package.json 中需设置 "type": "module"),否则会报错。
TypeScript 兼容:
若使用 TypeScript,需要将 tsconfig.json 中的 target 设置为 ES2022 或更高,并确保 moduleResolution 为 NodeNext 或 Node16。

errors

使用 import assertions 时候,遇到以下错误

The assert keyword in import attributes is deprecated and it has been replaced by the with keyword. You can enable the deprecatedImportAssert parser plugin to suppress this error. (18:38)


// 旧语法(已废弃)❌
// import carData from './car-data.json' assert { type: 'json' };

demos

import { readFile } from 'fs/promises';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';// 获取当前文件的目录路径(ES模块中没有 __dirname,需手动获取)
const __dirname = dirname(fileURLToPath(import.meta.url));
const jsonPath = join(__dirname, './data/car-prices.json');// 读取并解析 JSON
const loadCarData = async () => {try {const data = await readFile(jsonPath, 'utf8');return JSON.parse(data);} catch (err) {console.error('读取JSON失败:', err);throw err; // 抛出错误供上层处理}
};// 使用数据
const carData = await loadCarData();
console.log('2025年1月的Model Y价格:', carData["2025_01_13"]["Model Y"][0].price);

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://www.cnblogs.com/xgqfrms/p/17260205.html



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


http://www.hskmm.com/?act=detail&tid=37674

相关文章:

  • DeepSeek的“认知提纯”能力解析
  • 梦熊知更鸟赛水题题解合集 (两个人的演唱会 使一颗心免于哀伤 空气蛹)
  • CF2154D
  • Plya 定理学习笔记 | ABC428G 题解
  • 第十八天
  • 第十七天
  • vue3+elementPlus el-date-picker 自定义禁用状态hook 建立结束时间不能小于开始时间
  • [优先队列] P3611 [USACO17JAN] Cow Dance Show S 题解
  • 搜维尔科技将携手Xsens|Haption|Tesollo|Manus亮相IROS 2025国际智能机器人与系统会议
  • 【做题记录】贪心--提高组
  • 如何炫酷地使用集合划分容斥
  • 简单云计算算法--20251023
  • 处理空输入踩的坑
  • latex输入公式
  • 【为美好CTF献上祝福】 New Star 2025 逆向笔记
  • XXL-JOB(5)
  • 蛋白表达原理与关键要素解析
  • Ramanujan Master Theorem
  • 顾雅南的声音美化课堂
  • C++案例 自定义数组
  • 【周记】2025.10.13~2025.10.19
  • 背包
  • 10.23《程序员修炼之道 从小工到专家》第二章 注重实效的途径 - GENGAR
  • 玩转单片机之智能车小露——LED闪烁实战
  • ord() 函数
  • 2025.10.23总结 - A
  • 大模型 | VLA 初识及在自动驾驶场景中的应用
  • ExPRT.AI如何预测下一个将被利用的漏洞
  • Redis中的分布式锁之SETNX底层实现
  • 攻击模拟