首页 > 解决方案 > Ujson 适用于 MacOS,但不适用于 Ubuntu

问题描述

我已经将我在 MacOS 上工作的 Python 项目克隆到了新的 Ubuntu(虚拟)机器上。

我设法让它运行,但程序在以下行崩溃:

ujson.dumps(plist_as_file) # crash

错误是:

TypeError: � is not JSON serializable

我不知道那是哪个角色,也不知道在哪里找到。这plist_as_file是一个 mac *.plist 文件,使用以下行打开:

with open(plist_path, 'rb') as plist_as_file:

可能是 git 搞砸了一些东西,但由于 MacOS 和 Ubuntu 都是基于 Unix 的,我真的不知道怎么做。

有任何想法吗?

标签: pythonplistujson

解决方案


我认为该代码不适用于 MacOS 或 Ubuntu,因为 Apple 的 macOS 和 iOS .plist 文件不是JSON。他们遵循更多的 XML 格式,甚至在文档中这样说:

文件本身通常使用 Unicode UTF-8 编码进行编码,并且内容使用 XML 进行结构化。

在 Mac 或 Ubuntu 上运行代码:

import ujson

with open("Info.plist", 'r') as plist_as_file:
    ujson.dumps(plist_as_file)

将导致:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    ujson.dumps(plist_as_file)
TypeError: <_io.BufferedReader name='Info.plist'> is not JSON serializable

如果由于某种原因,您可以成功打开 .plist 并且没有收到该错误,那么您所拥有的不是实际的 .plist 文件。open无论文件模式是r还是,错误都是一样的rb

你说你得到了:

TypeError: � is not JSON serializable

我认为这是同样的错误,但由于某种原因,它没有正确打印出来。所以,ujson真的不是在这里使用合适的工具,而且它不是 Git 的问题。

Python 提供了一个用于读取/写入 .plist 文件的内置模块:plistlib

它具有与(或)模块相同的dump/dumpsload/loads方法。jsonujson

import plistlib

with open("Info.plist", 'rb') as plist_as_file:
    plist_data = plistlib.load(plist_as_file)

# The entire contents is stored as a dict
print(plist_data)

# Access specific content as a dict
print(plist_data["CFBundleShortVersionString"])
print(plist_data["UIMainStoryboardFile"])

推荐阅读