Home > Net >  Read data from a file to json array in python
Read data from a file to json array in python

Time:12-12

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']

CodePudding user response:

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)

CodePudding user response:

with open("test.json", "r") as f:
    res = f.read()
    res = [eval('{' i) for i in res.split('{') if i ]
print(res)
  • Related