1

I am trying to process some logs and post the log contents to an API for further processing. Before I post the data to the API I need to rename the keys but it doesn't seem to work.

This is what I have so far.

import re
import json

logs = ['2016-10-13 17:04:50 - info - uri:"GET x/y/z" ip:1.1.1.1 Rs:{"key1": "data", "key2":"data"}',
        '2016-10-13 17:05:10 - info - uri:"GET x/y/z" ip:1.1.1.1 Rs:{"key1": "data", "key2":"data"}']

newLogs = []
for log in logs:
    data = (re.compile(r"Rs:({[^}]*})").search(log)).group(1))
    data.replace('key1','keyA').replace('key2','keyB')
    newLogs.append(data)


# Current output - the keys are not changed
print (newLogs)
>>>> ['2016-10-13 17:04:50 - info - uri:"GET x/y/z" ip:1.1.1.1 Rs:{"key1": "data", "key2":"data"}',
      '2016-10-13 17:05:10 - info - uri:"GET x/y/z" ip:1.1.1.1 Rs:{"key1": "data", "key2":"data"}']

#Desired output
print (newLogs)
>>>> ['2016-10-13 17:04:50 - info - uri:"GET x/y/z" ip:1.1.1.1 Rs:{"keyA": "data", "keyB":"data"}',
      '2016-10-13 17:05:10 - info - uri:"GET x/y/z" ip:1.1.1.1 Rs:{"keyA": "data", "keyB":"data"}']
3
  • What is the problem? Are you getting an exception? Please update the question with the error you are getting. Commented Oct 20, 2016 at 7:34
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: minimal reproducible example. Commented Oct 20, 2016 at 7:36
  • @AKS I am trying to change key values but its not working. So there are not errors. Commented Oct 20, 2016 at 7:51

1 Answer 1

4

Strings are immutable in Python. So the method replace returns a new string, which you have to capture in some variable:

data = data.replace('key1','keyA').replace('key2','keyB')
Sign up to request clarification or add additional context in comments.

2 Comments

I cannot believe I made such a newbie error. I was rushing for my project so much that I completely forgot about it. This is purely a mistake on my end. Thank you for pointing it out.
This is fantastic, however, we cannot change the Dict and from this answer I converted Dict in to String and then renamed the key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.