python中的JSON对象钩子意外地将我的普通JSON更改为嵌套JSON

python中的JSON对象钩子意外地将我的普通JSON更改为嵌套JSON,python,json,Python,Json,我正在为学校学习Python。在最后一次作业中,我决定创建一个桌面任务应用程序,前端使用HTML/CSS/JS。我想用一个.txt文件来存储我的json数据,到目前为止一切正常 现在我在读取JSON数据并将其挂接到自定义对象时遇到了问题。 这是我的简单课程: class Task(dict): def __init__(self, title = "no title", description = "no description", priorit

我正在为学校学习Python。在最后一次作业中,我决定创建一个桌面任务应用程序,前端使用HTML/CSS/JS。我想用一个.txt文件来存储我的json数据,到目前为止一切正常

现在我在读取JSON数据并将其挂接到自定义对象时遇到了问题。 这是我的简单课程:

class Task(dict):
    def __init__(self, title = "no title", description = "no description", priority = 1):
        self.id = str(id(self))
        self.title = title
        self.description = description
        self.priority = priority
        user_tasks["tasks"].append(self.__dict__)
从.txt文件读取JSON时,我得到以下结果:

[{"id": "2145413512544", "title": "title", "description": "desc", "priority": 3}]
如果我尝试将JSON字符串挂接到自定义任务对象,如下所示:

json_tasks = json.loads(test, object_hook=Task)
因此,它将给我以下信息:

'description':'no description',
'id':'1460530367520',
'priority':1,
'title': {'description': 'desc', 'id': '2145413512544', 'priority': 3, 'title': 'title'}
'id':'2145413512544',
'title':'title',
'description':'desc',
'priority':3
有人知道这里发生了什么吗?如蒙帮助,将不胜感激:)


提前感谢。

使用
object\u hook=Task
似乎将我的整个JSON对象作为
title
参数。 我通过创建一个将JSON对象转换为任务的函数来解决这个问题,我将这个函数传递给了
object\u hook
,就像jasonharper说的那样

   user_tasks_json = json.loads(user_tasks_file_content, object_hook=create_task_from_json)
职能:

def create_task_from_json(json_obj):
    new_task = Task(id = json_obj.get("id"), 
                    title = json_obj.get("title"),
                    description = json_obj.get("description"),
                    priority = json_obj.get("priority"),
                    categoryid = json_obj.get("categoryid"))

似乎使用
object\u hook=Task
将我的整个JSON对象作为
title
参数。 我通过创建一个将JSON对象转换为任务的函数来解决这个问题,我将这个函数传递给了
object\u hook
,就像jasonharper说的那样

   user_tasks_json = json.loads(user_tasks_file_content, object_hook=create_task_from_json)
职能:

def create_task_from_json(json_obj):
    new_task = Task(id = json_obj.get("id"), 
                    title = json_obj.get("title"),
                    description = json_obj.get("description"),
                    priority = json_obj.get("priority"),
                    categoryid = json_obj.get("categoryid"))

您的类没有将正确的参数直接用作
object\u hook
选项。您需要一个只接受一个参数的东西,它将是一个字典,并使用它所需的各个参数调用您的类。由于JSON键和
\uuuu init\uuuu()
参数具有相同的名称,我认为这可能与
返回任务(**param)
一样简单。很抱歉,我不太明白您的意思。我在哪里调用
返回任务(**param)
?您将该行放入某个新函数中,然后将该函数(而不是
任务
本身)作为
对象钩子
传递。您的类没有将正确的参数直接用作
对象钩子
选项。您需要一个只接受一个参数的东西,它将是一个字典,并使用它所需的各个参数调用您的类。由于JSON键和
\uuuu init\uuuu()
参数具有相同的名称,我认为这可能与
返回任务(**param)
一样简单。很抱歉,我不太明白您的意思。我在哪里调用
返回任务(**param)
?您将该行放入某个新函数中,然后将该函数(而不是
任务本身)作为
对象钩子传递。