在换行符中记录JSON数组中的每个项

在换行符中记录JSON数组中的每个项,json,node.js,bash,Json,Node.js,Bash,我有这个: #!/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(

我有这个:

#!/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
,因为这是
forEach
函数的返回值。

它记录的
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的好方法,那就太好了。

这正好可以正常工作,只需使用换行符分隔数组中的项:

json_array=\''["one","two","three"]'\';

function getJSON {
   node -pe "JSON.parse($json_array).join('\n')"
}

getJSON | while read line; do
    echo "$line"
done

如果有人知道一种不使用奇怪转义字符声明json的好方法,那就太好了。

请编辑您的Q,以显示
$my\u json\u array
的可用值。祝你好运,就这么做了,谢谢你的帮助input@AlexanderMills:对于
getJSON
,没有循环的输出是什么?您还可以使用其他JSON语法感知解析器,如
jq
?请编辑您的Q以显示
$my\u JSON\u数组的可用值。祝你好运,就这么做了,谢谢你的帮助input@AlexanderMills:对于
getJSON
,没有循环的输出是什么?您还可以使用其他JSON语法感知解析器,如
jq
?您还可以尝试使用
some
函数,该函数将打印
false
,而不是
undefined
。您还可以尝试使用
some
函数,它将打印
false
,而不是
undefined
。您始终可以从JSON文件读取并按其内容声明数组。您始终可以从JSON文件读取并按其内容声明数组。