簡體   English   中英

在換行符中記錄JSON數組中的每個項目

[英]log every item in JSON array in newline

我有這個:

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

上面的問題,是它在末尾記錄“ undefined”:

one
two
three
undefined

它記錄的undefined與您指定的數組無關。 如果您在瀏覽器控制台中嘗試相同的代碼,則最后還會打印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而不使用奇怪的轉義字符的好方法,那將是很好的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM