I wrote this beauty a while back to run on a server and convert environment variables from JSON
to a bash .env
format.
#!/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? 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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.