Replace value in json during run time

Viewed 13806

I am trying to replace value on run time in json i.e.

Old

{
  "containerDefinitions": [{
    "name": "containername",
    "image": "myimage",
    "memory": 512,
    "cpu": 1,
    "essential": true,
    "portMappings": [{
      "hostPort": 80,
      "containerPort": 80,
      "protocol": "tcp"
    }]
  }],
  "volumes": [],
  "family": "containername"
}

New should be

{
  "containerDefinitions": [{
    "name": "containername",
    "image": "new image",
    "memory": 512,
    "cpu": 1,
    "essential": true,
    "portMappings": [{
      "hostPort": 80,
      "containerPort": 80,
      "protocol": "tcp"
    }]
  }],
  "volumes": [],
  "family": "containername"
}
  • Old value: - "image": "myimage"
  • New Value: - "image": "new image"

I want to do in bash. Is there any best way to do? Can we do through jq?

6 Answers

Given that linux does not by itself allow redirection to the same file, you can use the sponge utility from moreutils package

- apt update && apt install -y moreutils
- jq '.json_label="json_value"' file.json | sponge file.json

This will truly allow in line replacement;

If python is reliably present, then you can use embedded python like so:

  • setup multiline string
  • execute and fail on error

    #!/usr/bin/evn bash
    # python as multi line string
    
    read -r -d '' PYSCRIPT << ENDPY
    import json
    import os
    jsonfile = 'daemon.json'
    data = {}
    if os.path.exists(jsonfile):
        data = json.load(open(jsonfile))
    data["booleanVar"] = True
    data["stringVar"] = "foo"
    with open(jsonfile, 'w') as fp:
        json.dump(data, fp)
    ENDPY
    
    # execute python and fail on error
    
    echo "$PYSCRIPT" |python - || exit 1
    
Related