1

I have a file called usr.json, and this file contains a JSON object. The object looks as following:

{
  "users": {
          "accessRights":"FFFFF",
          "name": "admin"
         }
}

Now I want to replace the string for accessRights with a new value which is stored in a variable called newUsrCfg.

Since I'm working with a remote device I need to ssh to it, and for that I have a script.

However, I call all this in Python code:

def test_tc():
  newUsrCfg = "F7FFF"

  cmd = f'sed -ie \'s/\"accessRights\":.*/\"accessRights\": \"{newUsrCfg}\"/g\' "/etc/hgp/runtime/user/user1.json"'
  
  subprocess.call(["bash", pathToSshCommand, cmd])

The commands need to be either called with single quotes or double ones. And when opening the file the output of this is:

 {
      "users":{
               "accessRights": "f7fff"

I tried many other sed commands with different formats, but nothing worked.

buddemat
  • 4,552
  • 14
  • 29
  • 49
moab
  • 31
  • 6

1 Answers1

0

If jq is available to you, you can

jq '.users.accessRights = "f7fff"' usr.json                           

As also commented below, manipulating json with text replacement is likely to break if your input does not exactly meet your expectations (for instance though differences in whitespace). If you have a tool like jq which understands json, that is always the preferable option.

However, in case you still want to do it with sed you could adjust your regex to be less inclusive. Since you want to replace 5 hex values, something along the following lines should work (I hope I escaped everything correctly, can't test since I'm on the way).

cmd = 'sed -ie \'s/\"accessRights\":\s*\"[0-9,a-f,A-F]\{5\}\"/\"accessRights\": \"{newUsrCfg}\"/g\' "/etc/hgp/runtime/user/user1.json"'

See regex101.

A third option would to both load the file via ssh and manipulate the json in Python, or do it directly in Python on the target system, if Python is available there as well.

buddemat
  • 4,552
  • 14
  • 29
  • 49
  • Unfortunately, jq is not available – moab Aug 22 '22 at 12:46
  • 2
    @moab - It is available for most modern platforms. See https://stedolan.github.io/jq/download/ for a list ... though you wouldn't necessarily install it from there. And using a tool like `jq` is vastly superior to using hacky "edit as text" approaches that are liable to break when they encounter unexpected input files. – Stephen C Aug 22 '22 at 13:29
  • @moab, our duplicates also cover doing this with Python, which is available effectively everywhere. – Charles Duffy Aug 22 '22 at 17:32