如何将完整JSON内容存入单个环境变量?
将完整JSON设为环境变量的解决方案
根据不同终端环境,以下是可行的赋值方法:
Bash/Zsh(Linux/macOS)
单行赋值
用单引号包裹整个JSON内容,通过export设置环境变量:
export GOOGLE_APPLICATION_CREDENTIALS='{"type":"1234","project_id":"1234","private_key_id":"1234","private_key":"1234564789","client_email":"iam.gserviceaccount.com","client_id":"1072","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com","client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadatam"}'
多行赋值(保留JSON格式)
使用Here文档保持JSON的换行结构,避免压缩成单行:
export GOOGLE_APPLICATION_CREDENTIALS=$(cat << 'EOF' { "type":"1234", "project_id": "1234", "private_key_id": "1234", "private_key": "1234564789", "client_email": "iam.gserviceaccount.com", "client_id": "1072", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadatam" } EOF )
'EOF'的单引号可以防止内部内容被shell解析,确保JSON原样保存。
Windows CMD
将JSON压缩为单行,并用两个双引号转义内部的双引号,通过set赋值:
set GOOGLE_APPLICATION_CREDENTIALS="{\"type\":\"1234\",\"project_id\":\"1234\",\"private_key_id\":\"1234\",\"private_key\":\"1234564789\",\"client_email\":\"iam.gserviceaccount.com\",\"client_id\":\"1072\",\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"token_uri\":\"https://oauth2.googleapis.com/token\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com\",\"client_x509_cert_url\":\"https://www.googleapis.com/robot/v1/metadatam\"}"
Windows PowerShell
用单引号包裹JSON,通过$env:前缀设置环境变量:
多行版本
$env:GOOGLE_APPLICATION_CREDENTIALS = '{ "type":"1234", "project_id": "1234", "private_key_id": "1234", "private_key": "1234564789", "client_email": "iam.gserviceaccount.com", "client_id": "1072", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadatam" }'
单行版本
$env:GOOGLE_APPLICATION_CREDENTIALS = '{"type":"1234","project_id":"1234","private_key_id":"1234","private_key":"1234564789","client_email":"iam.gserviceaccount.com","client_id":"1072","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com","client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadatam"}'
关键说明
- 之前赋值失败是因为缺少正确的环境变量赋值语法(如
export/set/$env:),且未用引号包裹JSON导致shell将其解析为命令而非变量值。 - 若需要环境变量永久生效:
- Bash/Zsh:将赋值命令添加到
~/.bashrc或~/.zshrc文件中 - Windows CMD:通过系统属性添加到环境变量列表
- PowerShell:将命令写入
$PROFILE配置文件
- Bash/Zsh:将赋值命令添加到
内容的提问来源于stack exchange,提问作者pgmendormi
相关产品推荐
相关产品推荐

