python - 为什么我在流式传输时收到“JSONDecoderError”?
问题描述
使用模块 WebSockets 流式传输(加密)价格数据时出现 JSONDecoderError,我正在使用多处理。我在以前的类似问题中看到,大多数情况下单引号/双引号都存在问题,但对我来说并非如此。另外,我不会立即收到此错误。有人能帮我吗?
我的代码:
主文件
def main():
pairs = ["BTC/USDT", "ETH/USDT", "LTC/"]
for pair in pairs:
pairPrice = getPrice(pair)
if mainPrice != "0":
pass
def getPrice(pair:str):
path = CONSTS.allPairsPath + pair.replace("/", "") + ".json"
try:
with open(path) as f:
data = json.loads(f.read())
return [float(data["b"]), float(data["a"])]
except FileNotFoundError:
return "0"
if __name__ == "__main__":
p1 = Process(target=streaming.main)
p2 = Process(target=main)
p1.start()
p2.start()
p1.join()
p2.join()
流式传输.py
def main():
# Import own modules
import CONSTS
# Import built-in modules
import asyncio, json
# Import extern modules
import websockets
async def stream():
async with websockets.connect("wss://stream.binance.com:9443/ws/!bookTicker") as websocket:
while True:
data = await websocket.recv()
data = json.loads(data)
documentLoc = CONSTS.allPairsPath + data["s"] + ".json"
with open(documentLoc, "w+") as f:
f.write(str(data).replace("'", '"')) # replace single quotes by double quotes
loop = asyncio.get_event_loop()
asyncio.ensure_future(stream())
loop.run_forever()
示例 JSON 文件
{"u": 282430213, "s": "ADABTC", "b": "0.00000480", "B": "358426.00000000", "a": "0.00000481", "A": "26697.00000000"}
一段时间后(不是即时)我收到此“JSONDecoderError”错误消息:
Traceback (most recent call last):
File "/usr/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
self.run()
File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "main.py", line 13, in main
loop(mainPairs)
File "main.py", line 71, in loop
backwardsConvertPrice = getPrice(backwardsPair)[0] # Convert back to bitcoin
File "main.py", line 87, in getPrice
data = json.loads(f.read())
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
解决方案
推荐阅读
- neo4j - 在 Neo4j Graph Data Science 中,我可以使用自定义类型名称通过密码创建图形吗?
- python-3.x - Groupby 并在 Pandas 中打印整个数据框
- next.js - PWA 独立窗口是否有可能具有“保持领先”功能?
- c# - SQL 字符串或普通字符串
- python - 如何检测消费者是否已经在数据框中?
- database - 如何在数据库中删除表?以及如何创建视图表?
- python - 使用 ANN 进行多任务学习?
- php - 在 WooCommerce 单品页面添加产品类别链接
- html - 使用 CSS 完全不显示工具提示图标
- php - 移动浏览器在下载时将 .html 添加到文件名