我有一个使用python中的内存映射打开的json文件。我提供的大小为1024,即使json_file不包含那么多字段。当我执行json.loads(...)时,会得到Error: raise JSONDecodeError("Extra data", s, end)。我打开json文件,看到结尾处有NULL字符。查看此图像:python - 如何在python中使用mmap加载json? (在Windows上)-LMLPHP

我不确定加载json文件的正确方法。我打开mmap文件并加载json的代码如下。

The json file has contents shown below:
{
    "Gardens": {
        "Seaside": {
            "@loc": "porch",
            "@myID": "1.2.3",
            "Tid": "1",
            "InfoList": {
                "status": {
                    "@default": "0",
                    "@myID": "26"
                },
                "count": {
                    "@default": "0",
                    "@myID": "1"
                }
            },
            "BackYard": {
                "@loc": "backyard",
                "@myID": "75",
                "Tid": "2",
                "InfoList": {
                    "status": {
                        "@default": "6",
                        "@myID": "32"
                    },
                    "count": {
                        "@default": "0",
                        "@myID": "2"
                    }
                }
            }
        }
    }
} #  There are NULL characters here as doing the mmap fills NULL characters as the size of the file provided is 1024


        # Open and read file and MMAP (WRITE access)
        json_file = open(json_path, "r+", encoding="utf-8")
        mapped_file = mmap.mmap(json_file.fileno(), 1024, access=mmap.ACCESS_WRITE)

        # Create the mmap file buffer
        mappedFile.seek(0)
        file_size = os.path.getsize(json_path)
        buffer_for_json = mappedFile[:file_size]

        # Content is JSON, so load it
        json_data = json.loads(buffer_for_json.decode("utf-8")) # ERROR: raise JSONDecodeError("Extra data", s, end)


我真的迷路了,不确定如何解决这个问题。任何帮助,将不胜感激。 :)

最佳答案

当我一开始不import json时,这发生在我身上。

默认编码为'utf-8',因此我认为没有必要指定该编码。您也可以尝试json_data = json.loads(buffer_for_json.decode())
json_data = json.loads(buffer_for_json)

您可以阅读有关json here的更多信息,以及

10-05 17:58