Cryssie Cryssie - 1 month ago 9
JSON Question

Renaming a JSON key in Python

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"}']

Answer

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')
Comments