我想在下面的代码中输出
KNOCK_KNOCK="Who is there?"
TEST_FILE='{
"KNOCK_KNOCK": "Who is there?"
}'
for s in $(echo $TEST_FILE | jq -r "to_entries|map(\"\
(.key)=\(.value|tostring)\")|.[]" ); do
echo $s
done
我从这篇文章中得到了循环:Exporting JSON to environment variables
并且无法弄清楚如何进行修改以获取预期的输出。问题似乎是.value
中的空格对于以下测试用例,我得到了预期的结果:
TEST_FILE='{
"KNOCK_KNOCK": "Whoisthere?",
"POSTGRES_URI": "postgress://user:pass@testdb.com",
"WILL": "I.AM"
}'
for s in $(echo $TEST_FILE | jq -r "to_entries|map(\"\(.key)=\
(.value|tostring)\")|.[]" ); do
echo $s
done
KNOCK_KNOCK=Whoisthere?
POSTGRES_URI=postgress://user:pass@testdb.com
WILL=I.AM
我采用了以下对我有用的解决方案,但可以接受的答案是可以的。
TEST_FILE='{
"KNOCK_KNOCK": "Who is there?"
}'
echo $TEST_FILE | sed 's_[{}]__'| sed 's_: _=_' | sed 's_ _export _'
答案 0 :(得分:2)
您几乎明白了,但是您可以在此行中无循环地完成此操作:
$ echo '{"KNOCK_KNOCK": "Who is there?"}' | jq -r 'to_entries[] | .key + "=\"" + (.value|tostring) + "\""'
KNOCK_KNOCK="Who is there?"
to_entries
将您的对象转换为这样的对象数组:
$ echo '{"KNOCK_KNOCK": "Who is there?"}' | jq -r 'to_entries'
[
{
"key": "KNOCK_KNOCK",
"value": "Who is there?"
}
]
然后,您可以将每个数组元素与[]
一起使用,并使用key
和value
字段使用+
运算符进行简单的字符串连接。
答案 1 :(得分:2)
众多可能性之一:
//authentication for the hbs
app.use((req,res,next)=>{
if(req.isAuthenticated) res.locals.isAuthenticated = req.isAuthenticated();
next();
});
建议也使用jq -r 'to_entries[] | [.key,.value] | join("=")' <<< "$TEST_FILE"
:
@sh
请注意,如果您要使用$ echo $'{"KNOCK_KNOCK": "Who \'is\' there?"}'
| jq -r 'to_entries[] | [.key,(.value|@sh)] | join("=")'
KNOCK_KNOCK='Who '\''is'\'' there?'
$ KNOCK_KNOCK='Who '\''is'\'' there?'
$ echo "$KNOCK_KNOCK"
Who 'is' there?
$
,则可能需要使用双引号。