将环境变量转换为json文件 [英] Convert environment variables into a json file
问题描述
我试图找到一种方法来将配置设置输入到我的在容器中运行的SPA应用程序中.
I am trying to find a way to feed configuration settings into my SPA application that is running in a container.
我当前的计划是将配置作为环境变量传递.然后在容器启动时,根据这些环境变量生成一个json文件,并将其传递给浏览器(以及SPA应用程序).
My current plan is to pass in the configuration as environment variables. Then on container startup, generate a json file from those environment variables to pass to the browser (along with the SPA app).
我打算这样格式化我的环境变量:
I am planning to format my environment variables like this:
Env Variable Name: Security:ClientId
Env Variable Value: 123456
Env Variable Name: Security:clientSecret
Env Variable Value: abcdefg
Env Variable Name: AppSettings:Environment
Env Variable Value: Dev
它将转换为:
{
"AppSettings": {
"Environment": "Dev",
},
"Security": {
"ClientId": "123456",
"ClientSecret": "abcdefg"
}
}
我对shell脚本没有足够的经验,但是必须在shell脚本中完成,这样它才能在Linux容器中运行.
I am fairly inexperienced at shell scripting, but this has to be done in a shell script so it can run in a Linux container.
我已经阅读了 jq
,这似乎是在Shell脚本中与Json文件进行交互的方式.但是他们似乎都希望您从一个现有的json文件开始,然后将其转换为另一个json文件.
I have read of jq
, and it seems to be the way to interact with Json files in a shell script. But they all seem to want you to start with an existing json file that you will be transforming to a different json file.
如何通过键值对列表,子节并使用 jq
(或Shell脚本中的其他内容)创建新的json文件?
How do I create a new json file from a list of key value pairs, with sub sections and using jq
(or something else in a shell script)?
推荐答案
以下假设环境变量"名称和值可以作为变量=值字符串使用:
The following assumes the "environment variable" names and values could be made available as variable=value strings:
function data {
cat <<EOF
Security:ClientId=123456
Security:clientSecret=abcdefg
AppSettings:Environment=Dev
EOF
}
data | jq -nR '
def parse: capture("(?<x>[^:]*):(?<y>[^=]*)=(?<value>.*)");
reduce inputs as $line ({};
($line | parse) as $p
| .[$p.x][$p.y] = ($p.value) )
'
输出
如问号所示.
这篇关于将环境变量转换为json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!