Citizen SP
Citizen SP

Reputation: 1411

Bash: add object to a json file

I know how to echo / add text to the end of a file:

echo "{ "fruit":"apple" , "amount":"10" }" >> file.txt

My question is how to add a object to the json file below:

the file - file.txt (empty):

{
"fruit": [

]
}

Expected result:

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

]
}

Upvotes: 0

Views: 3192

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

Try this one:

$ sed -e '/"fruit":/a{ "fruit":"apple" , "amount":"10" }' file.txt

This will add a line after "fruit". If you want to replace the file with the modified text:

$ sed -i.bak -e '/"fruit":/a{ "fruit":"apple" , "amount":"10" }' file.txt

will add the line and replace the file with the modified content. The old file will be saved as backup file.txt.bak.

Upvotes: 0

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

ed is the standard text editor.

#!/bin/bash

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

Don't know why you want to use bash for that, though, there are much better tools around!

Done.

Upvotes: 6

Related Questions