以换行方式记录JSON数组中的每个项目

时间:2017-12-22 05:04:50

标签: json node.js bash

我有这个:

#!/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

2 个答案:

答案 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没有奇怪的转义字符,那就太好了。