我有这个JSON编码的文本:
{"port":27277,"velocityX":-0.4,"time":199888,"powerup":"Wall","player":0,"positionX":2331,"velocityY":4.2,"positionY":1130,"type":"powerupUse"}
{"port":27277,"velocityX":0,"time":199921,"powerup":"Homing Missile","player":0,"positionX":2319,"velocityY":0,"positionY":1179,"type":"powerupPickup"}
{"port":27277,"time":200032,"type":"pingSummary","pingByPlayer":{"0":0}}
{"port":27277,"velocityX":0.37,"time":201784,"powerup":"Homing Missile","player":0,"positionX":2346.61,"velocityY":4.25,"positionY":1123.58,"type":"powerupUse"}
{"port":27277,"time":202623,"player":0,"target":"turret","xp":1,"type":"structureDamage","exactXp":1.8466638326644897}
{"port":27277,"time":202623,"player":0,"target":"turret","xp":10,"type":"structureDestroy"}
{"port":27277,"time":202936,"player":0,"target":"turret","xp":2,"type":"structureDamage","exactXp":2.9056427478790283}
{"port":27277,"time":203171,"player":0,"target":"turret","xp":4,"type":"structureDamage","exactXp":4.7512664794921875}
{"port":27277,"time":205034,"type":"pingSummary","pingByPlayer":{"0":0}}
我想用Python解码它,我试过这个:
with open("log.txt") as log:
data = log.read()
jsondata = json.loads(data)
但是我收到了这个错误:
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 82)
我想解析像
这样的数据['port']['time']['player']
有人可以帮助我,因为我很快就需要这个吗?
答案 0 :(得分:4)
json.loads
加载单个JSON对象。在您的情况下,log.txt
包含由"\n"
分隔的多个JSON对象。您可以遍历文件中的行并在每个行上调用json.loads
:
with open("log.txt") as log:
jsondata = [json.loads(line) for line in log]
答案 1 :(得分:1)
问题是你在文件中有更多的jsons,而不仅仅是一个。使用" \ n"拆分文本分隔符,然后为每一行调用json.loads。
答案 2 :(得分:0)
我会做这样的事情:
import json
jsondata = 0
with open("log.txt") as log_file:
jsondata = [json.loads(line) for line in log_file]
for line in jsondata:
if 'port' in line:
print("Port: {}".format(line['port']))
if 'time' in line:
print("Time: {}".format(line['time']))
if 'player' in line:
print("Player: {}".format(line['player']))