如何在不使用eval函数的情况下使用python从文件的特定行读取json数组



我有一个文件,其中包含json数组

[
{'sector':'1','info':[{'id':'1234','pos':'55039974','risk':'low'},{'id':'3333','pos':'44530354','risk':'middle'}]},
{'sector':'2','info':[{'id':'2434','pos':'45455554','risk':'high'},{'id':'4444','pos':'4454555','risk':'high'}]}
]

作为单线

[{'sector':'1','info':[{'id':'1234','pos':'55039974','risk':'low'},{'id':'3333','pos':'44530354','risk':'middle'}]},{'sector':'2','info':[{'id':'2434','pos':'45455554','risk':'high'},{'id':'4444','pos':'4454555','risk':'high'}]}]

在文件中作为第2行。我如何从文件中读取json数组的第2行,并用打印它

print(str(lines[0]['sector'][0]['id']))

我不想使用eval函数,因为如果我使用像1E6条目这样的巨大数组,eval会将我的RAM增加到6Gb。这就是我试图弄清楚它如何与其他函数一起读取字符串并将其转换为数组的原因。thx寻求任何帮助

更新:我试过了:

with open('file.txt') as f:
""" 
v1: 
t = f.readlines()[2]
s = json.loads(t)
print(s[0]['sector'])
v1 output: 
Traceback (most recent call last): s = json.loads(t)
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
...
...
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
v2:
t = f.readlines()[2]
x = json.dumps(t, indent=4)
#x = json.dumps(t)
s = json.loads(x)
print(s[0]['sector'])
v2 output:
TypeError: string indices must be integers
v3:
t = f.readlines()[2]
x = json.dumps(t, indent=4)
s = json.JSONDecoder().decode(json.JSONEncoder().encode(x))
#s = json.JSONDecoder().decode(x)
#s = json.JSONEncoder().encode(x)
print(s[0]['sector'])
v3 output:
TypeError: string indices must be integers
"""

更新2数组有问题!没有[和扇区2工作

{"sector":"1","info":[{"id":"1234","pos":"55039974","risk":"low"},{"id":"RS11591147x","pos":"44530354","risk":"middle"}]}

更新3-(关闭(数组还可以,但我不得不将"to"替换为"to";在每个阵列中。并且存储器刚好从450Mb增加到700Mb。这是一个巨大的6Gb。问题是txt文件将vom 30Mb增加到50Mb,但谁在乎呢?xD

whereIsMyArray = 1
with open('file.txt', 'r') as fp:
line = fp.readlines()[whereIsMyArray].replace("'", '"')
data = json.loads(line)
print(data[1]['info'][1]["risk"])

您可以尝试使用json库函数json.loads:

import json
with open('yourfile.txt') as f:
s=f.readlines()[1]
result=json.loads(s)

最新更新