这是我用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)
我相信这是可以改进的。 非常感谢所有把这只小宝贝推向正确方向的人
使用标准库中的列表理解和^{} 函数
相关问题 更多 >
编程相关推荐