以换行方式记录JSON数组中的每个项目
我有这个:
#!/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
函数的返回值。