python - 将文件解析为json

时间:2017-06-05 14:10:38

标签: python json parsing

我有一些日志文件,我想从中提取数据并将其导出到json。

每次找到模式时,变量timestamp,line,frequency,crossbow,numberIt得到一个值,我这样做:

stringToJson.append({timestamp:00000, line:RRL, frequence:3434Hz, crossbow:TKESS44, numberIt: 2}) 然后我把它丢弃: json.dump(stringToJson, outfile)

结果是 [{timestamp:00000, line:RRL, frequence:3434Hz, crossbow:TKESS44, numberIt: 2},{timestamp:00000, line:RRL, frequence:3434Hz, crossbow:TKESS43, numberIt: 3},..., {timestamp:00001, line:CCL, frequence:8834Hz, crossbow:T1LS44, numberIt: 20}, {timestamp:00001, line:CCL, frequence:8834Hz, crossbow:T1LS45, numberIt: 21},..., ...]

我想要: [{00000:{" RRL":{" 3434Hz":{" TKESS44":5},{" TKESS44":5}} ,{00001:{" CCL":{" 8834Hz":{" T1LS44":20},{" T1LS45":20}} }}

我该怎么做?

干杯,

1 个答案:

答案 0 :(得分:1)

您的python代码正是您所要求的;你传给它一个字典(用时间戳,行和“频率”等键,并为其赋值),它给你一个“扁平”字典作为回报。

假设您的变量值与名称相对应,您可以稍微传递它们:line_valuefrequence_valuetimestamp_valuecrossbow_valuenumberIt_value

例如:

timestamp_value = "00000"
line_value = "RRL"
frequence_value = "3434Hz"
crossbow_value = "TKESS44"
numberIt_value = 2
stringToJson.append({str(timestamp_value) : {str(line_value) : {frequence_value : {str(crossbow_value) : int(numberIt_value)}}} })

给出

[{'00000': {'RRL': {'3434Hz': {'TKESS44': 2}}}}]

这就是您想要的,请记住,这样您就不会将密钥保留在字典中,因此您需要“知道”您正在构建的JSON结构。