[英]Using bash and jq and reading in a json file with \n in the contents
需要一些關於 jq 的幫助並讀取 json 文件,該文件必須具有 \n 值,因為我需要稍后將其導入其他內容。 我怎樣才能讓 jq 將其解釋為文字 \n 而不是下面的換行符......? 請注意我的 json 有一個 \n 我想要這樣。 我不希望它像在 output 中那樣將其視為回車
file.json(注意描述中的\n)
{
"person": [
{
"name": "Alex",
"age": "10",
"description": "A really\nnice kid"
},
{
"name": "James",
"age": "17",
"description": "One mature\nBoy who\ndoes his homework"
}
]
}
腳本:
jq -r -M '.person[] | .name + " " + .description' file.json \
| while IFS=$' ' read -r nameX descriptionX; do
echo "${nameX} ${descriptionX}"
echo "----------------------------------------done---------------------"
done
錯誤的 Output 現在它正在這樣做:
Alex A really
----------------------------------------done---------------------
nice kid
----------------------------------------done---------------------
James One mature
----------------------------------------done---------------------
Boy who
----------------------------------------done---------------------
does his homework
----------------------------------------done---------------------
它應該看起來像這樣,但它看起來像上面的那個。 我怎樣才能讓它看起來像這樣。
Alex A really\nnice kid
----------------------------------------done---------------------
James One mature\nBoy who\ndoes his homework
----------------------------------------done---------------------
您實際上可以直接在jq
中執行此操作,方法是用文字\
和n
字符替換實際的換行符(在 JSON 字符串中由\n
表示):
$ jq -r -M '.person[] | .name + " " + (.description | gsub("\n"; "\\n"))' file.json
Alex A really\nnice kid
James One mature\nBoy who\ndoes his homework
並將其輸入到您的while read
循環中:
$ jq -r -M '.person[] | .name + " " + (.description | gsub("\n"; "\\n"))' file.json |
> while IFS=$' ' read -r nameX descriptionX; do
> echo "${nameX} ${descriptionX}"
> echo "----------------------------------------done---------------------"
> done
Alex A really\nnice kid
----------------------------------------done---------------------
James One mature\nBoy who\ndoes his homework
----------------------------------------done---------------------
要求尚不清楚,因此這里有三種方法可能是(或可能是)解決方案的基礎:
jq -M '.person[] | .name + " " + .description' | sed -e 's/^"//' -e 's/"$//'
jq -M '.person[] | .name + " " + .description' |
while IFS=$' ' read -r line ; do
printf "%s\n" "$line" | sed -e 's/^"//' -e 's/"$//'
echo "----------------------------------------done---------------------"
done
jq -M '.person[] | .name, .description' |
threewhile IFS=$' ' read -r name ; do
name=$(sed -e 's/^"//' -e 's/"$//' <<< $name)
read -r description
description=$(sed -e 's/^"//' -e 's/"$//' <<< $description)
echo "$name $description"
echo "----------------------------------------done---------------------"
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.