0

I have a JSON file with the following text

{"category": "yyy", "id": "xxxyyy", "environment": "fff", "client": "000000", "user": "Alex", "log_time": "xxx", "source_context": null}

I need to find the the key user in that file and replace its value Alex with XXXX with exactly the same size (Alex = XXXX, Tom = XXX). I tried with sed command but I couldn't get it right.

3

You shouldn't parse JSON data with text oriented parser like sed. Instead use a JSON aware parser like jq.

If this tool is available on your system, you could simple do:

 jq '.user |= gsub(".";"X")' file

That replaces all string for the key user with the same number of X characters.

If your jq doesn't support gsub, you may use something like this:

jq '.user |= ([range(0;length)]|.[]="X"|add)' file
  • It also requires that jq is compiled with support for sub and related regular expression functions. The default (at least on some systems) is to not include support for these functions :-( Apart from that, this is probably the best approach (using a proper JSON parser, not sed etc.) – Kusalananda Oct 19 '18 at 10:07
  • Like you said, gsub is not supported. I get the following error. error: gsub is not defined .user |= gsub(".";"X") ^^^^ 1 compile error Can you please help in fixing it ? – user2181698 Oct 19 '18 at 10:13
  • @user2181698 Answer updated. I hope that your version will support used functions... – oliv Oct 19 '18 at 10:52
  • It doesn't work. I get the following error error: too few arguments to range (expected 2 but got 1) .user |= ([range(length)]|.[]="X"|add) ^^^^^ – user2181698 Oct 19 '18 at 11:16
  • 1
    @user2181698 Please avoid changing the scope of the question. Instead ask a new question stating the problem you've encountered. – oliv Oct 19 '18 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.