首页 > 解决方案 > 在类中打开转换为字典的 JSON 文件

问题描述

我正在打开并读取一个名为的 json 文件,例如,my_file.json位于..\config\my_file.json一个名为run_test.py. 最终,我想将 JSON 对象转换为 python 字典并在 python 中用它做其他事情。我正在从我的终端运行以下代码来执行该类:

python -c "from run_test import Update; x = Update('my_file.json'); print(x.why())"

这将返回:

Traceback (most recent call last): File "<string>", line 1, in <module> TypeError: why() missing 1 required positional argument: 'file_details'

我不知道为什么我会收到这个错误。当我运行时(return f在 read_file 的正文中):

python -c "from run_test import Update; x = Update('my_file.json'); print(x.read_file())

这会打印出我需要的字典。但是,我想把它传递给为什么我可以用那本字典做其他事情。然而,当我传递f到原因时,我得到了上述错误。为什么?

这是我正在使用的课程:

import json

class Update:
    def __init__(self, config_file_name):
        self.config_file_name = config_file_name

    def why(self, file_details):
        return file_details

    def read_file(self):
        f = json.load(open('..\config\\' + self.config_file_name))
        self.why(f)

标签: pythonjsonclassdictionary

解决方案


推荐阅读