Read data from a file to json array in python

Question:

I have a textfile called listtrades.txt

{'strike': 43700.0, 'exchangeid': 45754, 'ksinstrumenttoken': 18422, 'cepe': 'CE', 'quantity': 25, 'entry': 255, 'exit': 267.5, 'pnl': -312.5}
{'strike': 43700.0, 'exchangeid': 45755, 'ksinstrumenttoken': 18852, 'cepe': 'PE', 'quantity': 50, 'entry': 235.75, 'exit': 229, 'pnl': 337.5}
{'strike': 43800.0, 'exchangeid': 45756, 'ksinstrumenttoken': 18853, 'cepe': 'CE', 'quantity': 25, 'entry': 224.2, 'exit': 221.5, 'pnl': 67.49999999999972}

How do I read this to array so that I get the below output

lastrade = arrayobj[-1]

kstoken = lasttrade['ksinstumenttoken']
Asked By: user3698161

||

Answers:

So first of all this is not valid json you would need to refomat it to for example look like this:

[{"strike": 43700.0, "exchangeid": 45754, "ksinstrumenttoken": 18422, "cepe": "CE", "quantity": 25, "entry": 255, "exit": 267.5, "pnl": -312.5}, 
  {"strike": 43700.0, "exchangeid": 45755, "ksinstrumenttoken": 18852, "cepe": "PE", "quantity": 50, "entry": 235.75, "exit": 229, "pnl": 337.5}, 
  {"strike": 43800.0, "exchangeid": 45756, "ksinstrumenttoken": 18853, "cepe": "CE", "quantity": 25, "entry": 224.2, "exit": 221.5, "pnl": 67.49999999999972}]

To load this into python i would recommend this:

import json

with open("test.json", "r") as f:
    result = json.load(f)
Answered By: Teddy
with open("test.json", "r") as f:
    res = f.read()
    res = [eval('{'+i) for i in res.split('{') if i ]
print(res)
Answered By: Abhilash B
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.