python - 如何在 python 中使用 mmap 加载 json? (在 window 上)

标签 python json unicode utf-8 mmap

我有一个 json 文件,我使用 python 中的内存映射打开该文件。尽管 json_file 不包含那么多字段,但我提供的大小为 1024。当我执行 json.loads(...) 时,我收到 Error: raise JSONDecodeError("Extra data", s, end)。我打开json文件,看到末尾有NULL字符。请参阅此图片:nullcharacters

我不确定加载 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)

我真的很迷茫,不知道如何解决这个问题。任何帮助,将不胜感激。 :)

最佳答案

我无法测试这一点,因为我没有 Windows 来测试 Windows 版本的 mmap.mmap,但我认为这种情况正在发生:

当您调用mmap.mmap()且长度值大于文件大小时,磁盘上的原始文件将被更改。 docs说:

If length is larger than the current size of the file, the file is extended to contain length bytes.

最有可能的是,该文件用空字节填充到 1024 字节的大小(您指定的大小)。 1024 也是您之后从 os.path.getsize(json_path) 获取的值。 这就是为什么 mappedFile[:file_size] 包含这些尾随空字节。

我建议你有条件地设置mmap长度,例如:

json_file = open(json_path, "r+", encoding="utf-8")
length = min(1024, os.path.getsize(json_path))
mapped_file = mmap.mmap(json_file.fileno(), length, access=mmap.ACCESS_WRITE)

这应该避免空字节填充(顺便说一句,这也会永久损坏您的 JSON 文件。)。

关于python - 如何在 python 中使用 mmap 加载 json? (在 window 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57498036/

相关文章:

python - 将全角 Unicode 字符转换为 ASCII 字符

python - 最小化二值图像中的像素不均匀性

python - 在 Python 中生成 IP 范围

javascript - 如何在 React Native 中更改获取响应时的按钮?

Android 应用程序崩溃 : Parsing JSON into ListView

unicode - 从 utf8mb4_unicode_520_ci 升级 MariaDB 排序规则

C++如何将unicode字符转换为int

python - 如何仅将某些查询应用于具有属性异常的查询

python - 如何分隔列表中字符串的第一部分和最后一部分

php - 如何在多表中选择mysql并混合在一个json中?