Skip to main content
 首页 » 编程设计

python之在 Python 2.6 中加载时维护 JSON 文件的键顺序

2025年02月15日11Renyi-Fan

我正在使用 Python 2.6 加载 JSON 字符串。我想在加载时保持字符串的键顺序。我尝试使用此处的答案:Can I get JSON to load into an OrderedDict in Python?

因为我使用的是 Python 2.6,所以我确保将 simplejson as json 导入,但我仍然收到此错误:

TypeError: __init__() got an unexpected keyword argument 'object_pairs_hook' 

我错过了什么?

这是代码(截断):

import simplejson as json 
import ordereddict 
theJson = json.loads('{valid json}', object_pairs_hook=ordereddict.OrderedDict) 

如果我使用 import json 而不是 simplejson,同样的错误

请您参考如下方法:

您可以提供 simplejson 的更新本地副本。

下载 simplejson 源:

git clone https://github.com/simplejson/simplejson.git 

编译simplejson:

cd simplejson 
python setup.py build 

将 simplejson 打包为 egg(压缩的 Python 包):

python setup.py bdist_egg 

simplejson egg 将位于:

dist/simplejson-<version>-<python>-<os>-<arch>.egg 

其中 是simplejson版本, 是Python版本, 是操作系统, 是处理器架构。在我的机器上,这导致:

dist/simplejson-3.10.0-py2.7-linux-x86_64.egg 

将 simplejson egg 复制到可访问的地方(这可能只是您应用程序的本地目录)。现在在您的 Python 应用程序中,您必须告诉 Python 在哪里可以找到新版本的 simplejson:

import sys 
 
SIMPLEJSON_EGG = 'path/to/simplejson-....egg' 
sys.path.insert(1, SIMPLEJSON_EGG) 
 
import simplejson