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