如何创建从JSON文件提取数据的函数

2024-05-23 17:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在从一个JSON文件中提取交易数据以创建图形。我已经创建了一个文件来加载JSON数据,但是我想创建一个函数,允许我提取特定的数据点(比如getter?),我将如何进行呢? 因此,函数是存储数据,但我不知道如何将其连接回我加载的JSON文件

到目前为止,这是我的职责

class TradeInfo():
    
def __init__(self, sym, vol, pChange, gcount):
        self.symbol = sym
        self.volume = vol
        self.pChange = pChange
        self.gcount = gcount

    def getSymbol(self):
        return (self.symbol)

    def getVolume(self):
        return (self.volume)

    def getPriceChange(self):
        return (self.pChange)
    
    def getCount(self):
        return (self.gcount)

下面是我在单独的函数中加载Json文件时收到的输出 enter image description here

This is the code to load my JSON file
def loadfile(infileName,biDir= True):
    try:
        filename= infileName
        with open(filename) as f:
            fileObj = json.load(f)
            fileObj = json.dumps(fileObj, indent=4)
    except IOError as e:
        print("Error in file processing: " + str(e))
    return fileObj

Tags: 文件数据函数selfjsonreturndefload
1条回答
网友
1楼 · 发布于 2024-05-23 17:22:13

假设你的JSON看起来像这样:

{
    "marketId": "LTC-AUD",
    "bestBid": "67.62",
    "bestAsk": "68.15",
    "lastPrice": "67.75",
    "volume24h": "190.19169781",
    "volumeQte24h": "12885.48752662",
    "price24h": "1.37",
    "pricePct24h": "2.06",
    "low24h": "65.89",
    "high24h": "69.48",
    "timestamp": "2020-10-10T11:14:19.270000Z"
}

因此loadfile函数应该如下所示:

import json


def load_file(infile_name) -> dict:
    try:
        with open(infile_name) as f:
            return json.load(f)
    except IOError as e:
        print("Error in file processing: " + e)


data = load_file("sample_json.json")

print(json.dumps(data, indent=2, sort_keys=True))
print(data['timestamp'])

输出:

{
  "bestAsk": "68.15",
  "bestBid": "67.62",
  "high24h": "69.48",
  "lastPrice": "67.75",
  "low24h": "65.89",
  "marketId": "LTC-AUD",
  "price24h": "1.37",
  "pricePct24h": "2.06",
  "timestamp": "2020-10-10T11:14:19.270000Z",
  "volume24h": "190.19169781",
  "volumeQte24h": "12885.48752662"
}
2020-10-10T11:14:19.270000Z

我简化了您的函数并删除了一个冗余参数biDir,因为您没有在任何地方使用它

相关问题 更多 >