Find keys and replace corresponding values using Regex

Hi,

How do we find and replace a section in a string with regex using lookahead/lookbehind or something similar?

I have a nested json and want to find certain keys and replace corresponding values with REPLACED.

Note: I am not interested in JSON marshal/unmarshal/encode/decode solutions.

Thanks

Have

{
  "status": 200,
  "result": {
    "username": "john",
    "password": "Pa55w0rd",
    "eastings": 13452,
    "northings": 945,
    "admin": null,
    "codes": {
      "client_id": "E090000",
      "client_secret": "E119999",
      "ward": "W1"
    }
  }
}

WANT

{
  "status": 200,
  "result": {
    "username": "REPLACED",
    "password": "REPLACED",
    "eastings": 13452,
    "northings": 945,
    "admin": null,
    "codes": {
      "client_id": "REPLACED",
      "client_secret": "REPLACED",
      "ward": "W1"
    }
  }
}

I recommend you to use gjson and sjson for json editing.
Or you can convert the json into a map, edit it and then convert it back into json.

1 Like

Start with regexp package - regexp - Go Packages and adapt it for you data.

Regexs are brittle which is why people suggest that you use a proper JSON parser.