jq + what is the right approach to replace word that retruned 56 times in json

Issue

we have the following json file ( example with grep )

grep DB_SERVER_CV02.localdomain /home/main.json

 "hadoop.proxyuser.ambari.hosts": "DB_SERVER_CV02.localdomain",
                    "yarn.timeline-service.http-authentication.proxyuser.ambari.hosts": "DB_SERVER_CV02.localdomain",
                    "timeline.metrics.service.webapp.address": "DB_SERVER_CV02.localdomain:6188",
                    "javax.jdo.option.ConnectionURL": "jdbc:postgresql://DB_SERVER_CV02.localdomain:5432/hive",
                    "webhcat.proxyuser.ambari.hosts": "DB_SERVER_CV02.localdomain",
                    .
                    .
                    .
                    .
                    .
                    

DB_SERVER_CV02.localdomain word appears more then 56 times in the main.json file

and we want to replace the DB_SERVER_CV02.localdomain with APP_SERVER_CV02.localdomain name

the easy way is just to do it with sed as

            sed -i s'/DB_SERVER_CV02.localdomain/APP_SERVER_CV02.localdomain/g' /home/main.json
                
                

but as I understand better to works with jq when dealing with json files

what is the right approach to replace the DB_SERVER_CV02.localdomain with APP_SERVER_CV02.localdomain with jq ?

Solution

In the absence of further information, you might consider a "global search and replace" on strings (apart from keys):

walk(if type == "string" 
     then sub("DB_SERVER_CV02[.]localdomain"; "APP_SERVER_CV02.localdomain") 
     else . end)

You may wish to tweak the sub command (or change it to gsub), depending on your actual requirements.

(You could include the above walk program on the command line, but I’d recommend putting it into a file and using jq with the -f option.)

If you want to change all occurrences, even in keys, then you might be able to use sed, but you could also use jq with walk along the lines shown above but using with_entries for the keys. Since you haven’t specifically mentioned this, though, it can perhaps be left as an exercise.

Answered By – peak

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published