如何改进日志转换器?

2024-10-01 11:39:36 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我用Python编写的第一段代码。它应该将一个.json文件转换成json对象。 .json文件如下所示:

编辑:我必须依靠字符串“Title\”来分隔我的“columns”。 “items”是随机字符串,但每个标题的项数完全相同

[
  "Title_1",
  "Item1",
  "Item2",
  "Item3",
  "Title_2",
  "Item1",
  "Item2",
  "Item3",
  "Title_3",
  "Item1",
  "Item2",
  "Item3",
]

最终结果应类似于以下列表:

{"somekey":"item1","anotherkey":"item1", "yetanotherkey":"item1"}
etc...

这是我想出的一段绝妙的代码:

def convertJSON(file_name):
'''
:param file_name:
:return: single log_messages JSON object with JSON array of log_messages    
as value
'''
  log = open(file_name, 'r')
  logaslist = list(log)
  #remove opening and closing brackets
  preppedlogaslist = logaslist[1:-1]
  templist = []
  listoflists = []
  #loop trough list and park items in listoflists
  for t in preppedlogaslist:
    if "Title_" in t:
        if listoflists is not None and len(templist) is not 0:
            listoflists.append(templist)
            templist = []
    else:
        templist.append(t[2:-3])
  listoflists.append(templist)
  #create JSON object
  agedayslist = listoflists[0]
  ageweekslist = listoflists[1]
  messagelist = listoflists[2]
  jsondict = []
  for i in range(len(messagelist)):
    jsondict.append({'age_days':agedayslist[i],'age_weeks':ageweekslist[i],
    'message':messagelist[i]})
return json.dumps(jsondict)

我相信这是可以改进的。 非常感谢所有把这只小宝贝推向正确方向的人


Tags: andnameinlogjsontitlefileappend
1条回答
网友
1楼 · 发布于 2024-10-01 11:39:36

使用标准库中的列表理解和^{}函数

>>> import json
>>> f = json.loads('["Title_1","Item1","Item2","Item3","Title_2","Item1","Item2","Item3","Title_3","Item1","Item2","Item3"]')
>>> dict((item.lower()+'key', item) for item in f if not item.startswith('Title_'))
{'item1key': 'Item1', 'item2key': 'Item2', 'item3key': 'Item3'}

相关问题 更多 >