Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add json object to json file using shell script

Tags:

json

linux

shell

json file as follows:

{"name" :"sam",
"age":23,
"designation":"doctor"}

now i want to add another json object {"location":"canada"} at the end of the file using bash script i have tried echo "{"location":"canada"}">>sample.json

but it results

{"name" :"sam",
"age":23,
"designation":"doctor"} {location:canada}

but i want it to be like this

{"name" :"sam",
"age":23,
"designation":"doctor", 
"location":"canada"}

please suggest me

like image 952
user2353439 Avatar asked Sep 05 '25 03:09

user2353439


2 Answers

To merge two json objects, you could use jq command-line utility:

$ jq -s add sample.json another.json

Output:

{
  "name": "sam",
  "age": 23,
  "designation": "doctor",
  "location": "canada"
}

To update a single attribute:

$ jq '.location="canada"' sample.json

It produces the same output.

To prepend "doctor" to the location:

$ jq '.location = "doctor" + .location' input.json

Output:

{
  "name": "sam",
  "age": 23,
  "designation": "doctor",
  "location": "doctorcanada"
}
like image 137
jfs Avatar answered Sep 08 '25 00:09

jfs


sed -i '$s/}/,\n"location":"canada"}/' sample.json

Result:

{"name" :"sam",
"age":23,
"designation":"doctor",
"location":"canada"}
like image 28
perreal Avatar answered Sep 07 '25 23:09

perreal