0

I need to find and replace a big part of a json file using shell. For exemple I have this file :

{
  
  "Balise1": true,
  "Balise2": true,
  "OtherThingEnabled": false,
  "proxySettings": {
    "port": 0
  },
  "mailSettings": {},
  "maxRunningActivitiesPerJob": 5,
  "maxRunningActivities": 5,
}

I need to clear what's inside the brackets of the "proxySettings" and replace it with :

"proxySettings": {
    "host": "my-proxy.host.com",
    "port": 80
}

I can't be sure how many lines there will be in the file at the beggining. Could be one, several or none. The only thing I am sure, is the brackets. I need it to be properly indent.

I've looked sed function using redex, but I am stuck with the number of line being unknown.

Could you help ? Thanks

1
  • Hello, do you need to use sed or other tools would work for you ? As your file is a valid json file tool aware should be used Commented Dec 13, 2022 at 10:24

1 Answer 1

0

Using the JSON processor jq (and assuming that the input is valid JSON, which the posted document is not as it contains a trailing comma):

jq '.proxySettings = { host: "my-proxy.host.com", port: 80 }' file.json

This sets the proxySettings section to the given values, overwriting whatever other value the key was previously associated with, if any.

If you want to pass the two values on the command line, possibly from shell variables, use

myproxy=my-proxy.host.com
myport=80

jq --arg host "$myproxy" --argjson port "$myport" '.proxySettings = { host: $host, port: $port }' file.json

or the shorter

myproxy=my-proxy.host.com
myport=80

jq --arg host "$myproxy" --argjson port "$myport" '.proxySettings = $ARGS.named' file.json

This last variation creates an internal jq object $ARGS.named that contains the two keys, host and port, with the values given on the command line. This object is assigned to the proxySettings section in the input document.

The reason we use --arg for the host name and --argjson for the port number is that the host name is a string that needs to be JSON encoded, but the port number is a numeric value that should not be encoded as a JSON string.

The result is, in all cases, written to standard output. Redirect it to a new filename, or pipe it to sponge file.json to overwrite the original file with the output.

1
  • Thank you for that quick answer. Unfortunatly, the file that is provided by the software does contain some trailing comma... I am still going to test it. As soon as I am able to install jq.
    – Raph04
    Commented Dec 13, 2022 at 13:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .