Stam Kaly Stam Kaly - 5 months ago 21
Python Question

How to decode JSON where the values are separated in lines

I have this JSON encoded text:

{"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}}


I want to decode it in Python and I've tried this:

with open("log.txt") as log:
data = log.read()
jsondata = json.loads(data)


But I get this error:

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 82)


I want to parse data like

['port']['time']['player']


Could someone help me with this because I need this soon?

Answer

json.loads loads a single JSON object. In your case, log.txt contains multiple JSON objects separated by "\n". You can iterate over the lines in the file and call json.loads on each of them:

with open("log.txt") as log:
    jsondata = [json.loads(line) for line in log]
Comments