在Python中重命名JSON密钥

时间:2016-10-20 07:31:43

标签: python json

我正在尝试处理一些日志并将日志内容发布到API以进行进一步处理。在我将数据发布到API之前,我需要重命名密钥,但它似乎不起作用。

这是我到目前为止所做的。

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

1 个答案:

答案 0 :(得分:2)

字符串在Python中是不可变的。因此方法function pad(num) { return String("0"+num).slice(-2); } function formatDate(date) { return date.getFullYear()+pad(date.getMonth()+1)+date.getDate(); } var date = new Date("Tue Jul 14 02:00:00 PDT 2015"); console.log(formatDate(date)); 返回一个新字符串,您必须在某个变量中捕获它:

replace