如何改进LogConverter?

时间:2015-02-27 10:38:19

标签: python

这是我在Python中的第一段代码。它应该将.json文件转换为json对象。 .json文件如下所示:

编辑:我必须依赖字符串“Title_”来分隔我的“列”。 '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)

我确信这可以改进。 非常感谢任何能够朝着正确的方向推动这只小蚯蚓的人。

1 个答案:

答案 0 :(得分:1)

使用列表推导和标准库中的json.load函数。

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