简体   繁体   中英

how to add json object to json file using shell script

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

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"
}
sed -i '$s/}/,\n"location":"canada"}/' sample.json

Result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM