Python和livejson类型对象'_NestedList'无法序列化为JSON

2024-10-03 00:20:17 发布

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

好吧,我试着做一个字典重命名函数,但是我不断得到错误Object of type '_NestedList' is not JSON serializable不管我做什么,我试过一些事情,当我在repl上试的时候,它们没有问题。。。除非我把它们放在我这边。你知道吗

它的json看起来像custom["commands"]["command"]["beep"]
所以我想把它改成custom["commands"]["command"]["boom"]

{
    "command": {},
    "commands": {
        "command": {
            "beep": {
                "created": "2018-11-04 16:32:50.013260",
                "created2": 1541349170.0132835,
                "createdby": "me",
                "disablefor": [],
                "enabledfor": [],
                "message": "asd",
                "public": "self",
                "type": "text",
                "unsendtimer": 0,
                "unsendtrigger": false
            },
            "bep": {
                "created": "2018-11-04 16:34:38.723840",
                "created2": 1541349278.7238638,
                "createdby": "me",
                "disablefor": [],
                "enabledfor": [],
                "message": "asd",
                "public": "self",
                "type": "text",
                "unsendtimer": 0,
                "unsendtrigger": false
            },
            "boop": {
                "STKID": "423",
                "STKPKGID": "1",
                "STKVER": "100",
                "created": "2018-10-27 00:53:38.067740",
                "created2": 1540601618.0677645,
                "createdby": "me",
                "disablefor": [
                    "u69a0086845f2d38c5ecfd91a7601f3c1",
                    "ua2ed27b7932f647b492daa68ef33c0cc"
                ],
                "enabledfor": [],
                "message": "8775249726676",
                "public": "on",
                "type": "sticker",
                "unsendtimer": 0,
                "unsendtrigger": true
            }
        },
        "commandgrab": false,
        "commandgroup": ""
    }
}

这就是json文件的样子,有人有什么建议我很乐意,谢谢


Tags: jsonfalsemessagetypepubliccommandcommandsme
1条回答
网友
1楼 · 发布于 2024-10-03 00:20:17

您使用的是livejson包,而不是python的内置json包。你知道吗

livejson结构是livejson对象的树;显然livejson不直接支持在键之间移动这些对象:

>>> import livejson
>>> test['foo'] = {'bar': {'baz': [1, 2, 3]}
>>> test
{'foo': {'bar': {'baz': [1, 2, 3]}}}

>>> type(test['foo']['bar']['baz'])
<class 'livejson._NestedList'>


>>> test['foo']['bar']['quux'] = test['foo']['bar']['baz']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ...
TypeError: Object of type _NestedList is not JSON serializable

livejson对象有一个data属性,它返回livejson正在包装的标准python列表和dict,因此需要使用此属性来重新分配键的值:

>>> test['foo']['bar']['quux'] = test['foo']['bar']['baz'].data

# Now remove the old value
>>> del test['foo']['bar']['baz']
>>> test

{'foo': {'bar': {'quux': [1, 2, 3]}}}

相关问题 更多 >