python - 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 的,我真的不知道怎么做。
有任何想法吗?
解决方案
我认为该代码不适用于 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
/dumps
和load
/loads
方法。json
ujson
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"])
推荐阅读
- java - 在 Java 中旋转 N * M 矩阵
- css - 自定义顺风下拉扩展父容器
- python - Python-Pandas:使用每日和每周数据检查 2 个 DF 上的两个值是否为真
- python - 检查适度的数字。如何包含 numLen<1 ---> 返回编号不能拆分的条件”
- python - 在 Django 中创建多个相关对象的最佳实践
- react-native - new Tflite() 返回空对象
- bash - 通过命令行而不是通过 crontab 调用 STRAVA 脚本时,Bash HTTPie 有效
- linux - 如何设置 RPi 以自动 ssh 端口转发到通过以太网连接到 RPi 的设备?
- r - 根据列值从 data.frame 中随机选择行
- python - 如何在python3中计算天或月的时差