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

问题描述 投票:0回答:2

我有这个:

#!/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
json node.js bash
2个回答
1
投票

它记录的undefined与您指定的数组无关。如果你在浏览器控制台中尝试相同的代码,它也会在最后打印undefined,因为这是forEach函数的返回值。


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

© www.soinside.com 2019 - 2024. All rights reserved.