簡體   English   中英

如何在不使用 eval function 的情況下使用 python 從文件的特定行讀取 json 數組

[英]how to read a json array from specific line of a file with python without using eval function

我有一個包含 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 行。我怎樣才能從該文件中讀取第 2 行,即 json 數組並用

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

? 我不想使用 eval function,因為如果我使用像 1E6 條目這樣的巨大數組,eval 會將我的 RAM 增加到 6Gb。 這就是我試圖弄清楚它如何與其他函數一起讀取字符串並將其轉換為數組的原因。 謝謝任何幫助

更新:我試過:

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 - (關閉)陣列沒問題,但我不得不將每個陣列中的 ' 替換為 "。memory 只是從 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 庫 function json.loads

import json

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

result=json.loads(s)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM