我有这个:
#!/usr/bin/env bash
node -pe "JSON.parse('[\"one\",\"two\",\"three\"]')" | while read line; do
echo "$line"
done
只记录一行:
[ '一二三' ]
说我有一个JSON的env变量:
json_array=\''["one","two","three"]'\';
function getJSON {
node -pe "JSON.parse($json_array).forEach(v => console.log(v))"
}
getJSON | while read line; do
echo "$line"
done
上面的问题是,它最后是“未定义”:
one
two
three
undefined
它记录的undefined
与您指定的数组无关。如果你在浏览器控制台中尝试相同的代码,它也会在最后打印undefined
,因为这是forEach
函数的返回值。
这恰好工作正常,只需要用换行符分隔数组中的项:
json_array=\''["one","two","three"]'\';
function getJSON {
node -pe "JSON.parse($json_array).join('\n')"
}
getJSON | while read line; do
echo "$line"
done
如果有人知道一个很好的方法来声明json而没有奇怪的转义字符,那就太好了。