You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JSON文件中传入环境变量值并设置布尔属性?

实现环境变量注入JSON文件的方法

你的目标是将环境变量PUBLIC_VALUE的值转换为布尔值后,替换JSON文件中report.public的占位符,以下是两种实用实现方式:

方法一:Node.js 脚本实现

适合已有Node.js环境的场景,能准确处理布尔值的格式转换:

  1. 创建注入脚本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));
  1. 运行脚本:
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 10:37:57