简体   繁体   English

将JSON转换为bash环境变量

[英]Convert JSON to bash environment variables

I wrote this beauty a while back to run on a server and convert environment variables from JSON to a bash .env format. 我写了一段时间回来在服务器上运行并将环境变量从JSON转换为bash .env格式。

#!/usr/bin/env node
var strings = []
process.stdin.resume()
process.stdin.setEncoding('utf8')
process.stdin.on('data', function(data) {
  var json = JSON.parse(data)
  for (var key in json) {
    var val = json[key]
    strings.push(key + '="' + val + '"')
  }
})
process.stdin.on('end', function() {
  var output = strings.join('\n')
  process.stdout.write(output)
})

Can this be done without node, just bash? 这可以在没有节点的情况下完成,只需要bash吗? I'm having trouble getting this working on a server without node installed or without the correct path specified. 我在没有安装节点或没有指定正确路径的服务器上工作时遇到了麻烦。

Yes, assuming that all the key/val pairs you want to keep are in the form: 是的,假设您要保留的所有键/值对都采用以下形式:

"key":"stringval"
"key":numval
"key":true or false or null

(with optional space around the colon): (在冒号周围有可选的空格):

#!/bin/sh
tr -d '\n' |
  grep -o '"[A-Za-z_][A-Za-z_0-9]\+"\s*:\s*\("[^"]\+"\|[0-9\.]\+\|true\|false\|null\)' |
  sed 's/"\(.*\)"\s*:\s*"\?\([^"]\+\)"\?/\1="\2"/'

Example: 例:

cat manifest.json | ./json2env.sh

yields 产量

name="Polymer Starter Kit"
short_name="Polymer Starter Kit"
src="images/touch/icon-72x72.png"
sizes="72x72"
type="image/png"
test1="0.123"
test2="true"
test3="false"
test4="null"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM