curious_brain
curious_brain

Reputation: 403

How can I replace a character in a specific JSON field?

If I have a file with such content:

{"id":"doi-platelemetry-doi/doiplatelemetry","name":"doi/doiplatelemetry","location":"doi/doiplatelemetry/2.0.0/doiplatelemetry:2.0.0_49","component":"doi","tag":"2.0.0_49"},{"id":"doi-maintenance-service-doi/maintenance-service","name":"doi/maintenance-service","location":"doi/1.0.0/maintenance-service:1.0.0.681","component":"doi","tag":"1.0.0.681"}

How do we replace all / with - only in the value of location field? Meaning, after the replacement, the file content should be:

{"id":"doi-platelemetry-doi/doiplatelemetry","name":"doi/doiplatelemetry","location":"doi-doiplatelemetry-2.0.0-doiplatelemetry:2.0.0_49","component":"doi","tag":"2.0.0_49"},{"id":"doi-maintenance-service-doi/maintenance-service","name":"doi/maintenance-service","location":"doi-1.0.0-maintenance-service:1.0.0.681","component":"doi","tag":"1.0.0.681"}

This can be very easily achieved using jq but I am looking for a solution that works even when tools like jq are not available.

Upvotes: 0

Views: 96

Answers (1)

Raman Sailopal
Raman Sailopal

Reputation: 12877

With awk:

awk -F, 'BEGIN { RS=","} /location/ { gsub("/","-",$0) } {ORS=","}1' file > file.tmp && mv -f file.tmp file

Set the record separator to "," and then when the record contains location, using gsub to replace all "/" for "-"

Upvotes: 1

Related Questions