Bash:将对象添加到json文件

Cit*_* SP 0 linux bash shell

我知道如何回显/添加文本到文件的末尾:

echo "{ "fruit":"apple" , "amount":"10" }" >> file.txt
Run Code Online (Sandbox Code Playgroud)

我的问题是如何将对象添加到下面的json文件:

文件 - file.txt(空):

{
"fruit": [

]
}
Run Code Online (Sandbox Code Playgroud)

预期结果:

{
"fruit": [
{ "fruit":"apple" , "amount":"10" } #object to add

]
}
Run Code Online (Sandbox Code Playgroud)

gni*_*urf 6

ed 是标准的文本编辑器.

#!/bin/bash

{
ed -s file.json <<EOF
/\"fruit\": \[
a
{ "fruit":"apple" , "amount":"10" } #object to add
.
wq
EOF
} &> /dev/null
Run Code Online (Sandbox Code Playgroud)

不知道你为什么要使用bash,但是,周围有更好的工具!

完成.