如何在JSON文件中传入环境变量值并设置布尔属性?
实现环境变量注入JSON文件的方法
你的目标是将环境变量PUBLIC_VALUE的值转换为布尔值后,替换JSON文件中report.public的占位符,以下是两种实用实现方式:
方法一:Node.js 脚本实现
适合已有Node.js环境的场景,能准确处理布尔值的格式转换:
- 创建注入脚本
inject-env.js:
const fs = require('fs'); // 读取目标JSON文件 const rawJson = fs.readFileSync('./sample.json', 'utf8'); const jsonData = JSON.parse(rawJson); // 读取环境变量并转换为布尔值(兼容大小写输入) const publicEnvValue = process.env.PUBLIC_VALUE?.toLowerCase() === 'true'; // 更新JSON属性 jsonData.report.public = publicEnvValue; // 格式化写回文件 fs.writeFileSync('./sample.json', JSON.stringify(jsonData, null, 2));
- 运行脚本:
- Linux/macOS终端:
PUBLIC_VALUE=true node inject-env.js - Windows CMD:
set PUBLIC_VALUE=true && node inject-env.js - Windows PowerShell:
$env:PUBLIC_VALUE='true'; node inject-env.js
方法二:Shell/PowerShell 命令替换
适合无Node.js环境的场景,直接通过文本替换实现:
Linux/macOS(sed命令)
# 设置环境变量(可替换为false) export PUBLIC_VALUE=true # 替换占位符 sed -i '' "s/process.env.PUBLIC_VALUE/$PUBLIC_VALUE/g" sample.json
注:Linux系统下执行sed命令无需加'',直接用sed -i "s/process.env.PUBLIC_VALUE/$PUBLIC_VALUE/g" sample.json
Windows PowerShell
$env:PUBLIC_VALUE = "true" (Get-Content sample.json) -replace 'process.env.PUBLIC_VALUE', $env:PUBLIC_VALUE | Set-Content sample.json
内容的提问来源于stack exchange,提问作者Sourav Mehra
相关产品推荐
相关产品推荐

