简体   繁体   English

从文件中读取数据到python中的json数组

[英]Read data from a file to json array in python

I have a textfile called listtrades.txt我有一个名为 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我如何将其读入数组以便获得以下 output

lastrade = arrayobj[-1]

kstoken = lasttrade['ksinstumenttoken']

So first of all this is not valid json you would need to refomat it to for example look like this:所以首先这是无效的 json 你需要重新格式化它,例如看起来像这样:

[{"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:要将其加载到 python 中,我建议这样做:

import json

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM