Reputation: 150
I a have a JSON file in which a JSON object needs to be deleted. Is there any way to delete it by using the sed command only? My sample file is given below.
{
"name": "ABC",
"description": "XYZ",
"versions": {},
"json_class": "Chef::Environment",
"chef_type": "environment",
"default_attributes": {},
"override_attributes": {
"company": {
"xyz": {
"mailer": {
"smtp_host": "Some IP",
"imap_host": "Some Host",
"imap_user": "Some UserId",
"reply_to": "Some User Id",
"outbound_user": "",
"imap_mail_domain": "compute.oraclecloud.com",
"imap_password": ""
},
"logicaldomainname": ""
}
}
}
}
I want to delete the mailer object from the file using the sed command. Please take a look and let me know if it is possible using the sed command.
My main motive of this deletion is to replace this object with new mailer object so that the next time when another mailer object will be posted then we will append it in xyz JSON object.
Expected output:
{
"name": "ABC",
"description": "",
"version": {},
"json_class": "Chef::Environment",
"chef_type": "environment",
"default_attributes": {},
"override_attributes": {
"Company": {
"XYZ": {
"logicaldomainname": ""
}
}
}
}
Upvotes: 4
Views: 15035
Reputation: 2399
Using sed
:
sed '/\"mailer\"/,/}/ d; /^$/d' 1.a
"Delete from mailer
to the first }
, then delete all blank lines (you input has one)".
To overwrite the file ("in-place")
sed -i ...
Note: works for multiline files (as yours).
Upvotes: 10
Reputation: 530960
You should strongly consider resolving the licensing issue that prohibits jq
:
jq 'del(.override_attributes.company.xyz.mailer) | .description=""' input.json
Upvotes: 7
Reputation: 203219
$ awk -v RS='^$' -v ORS= '{sub(/"mailer":[^}]+},[[:space:]]+/,"")}1' file
{
"name": "ABC",
"description": "",
"versions": {
},
"json_class": "Chef::Environment",
"chef_type": "environment",
"default_attributes": {
},
"override_attributes": {
"Company": {
"XYZ": {
"logicaldomainname": ""
}
}
}
}
The above uses GNU awk for multi-char RS, with other awks you'd build up the record one line at a time and handle it in the END section:
$ awk -v ORS= '{rec=rec $0 RS} END{sub(/"mailer":[^}]+},[[:space:]]+/,"",rec); print rec}' file
{
"name": "ABC",
"description": "",
"versions": {
},
"json_class": "Chef::Environment",
"chef_type": "environment",
"default_attributes": {
},
"override_attributes": {
"Company": {
"XYZ": {
"logicaldomainname": ""
}
}
}
}
Upvotes: 2