我正在尝试在Can I get JSON to load into an OrderedDict in Python?中的mjhm回答之后将json文件加载到OrderedDict。为简单起见,我从一个json字符串开始,代码是:
#!/usr/bin/python
import simplejson as json
import ordereddict
testjson='{ "foo": 1, "bar": 2 }'
my_ordered_dict = json.loads(testjson, object_pairs_hook=ordereddict.OrderedDict)
但是,运行上述内容时出现以下错误:
Traceback (most recent call last):
File "./l.py", line 8, in <module>
my_ordered_dict = json.loads(testjson, object_pairs_hook=ordereddict.OrderedDict)
File "/usr/lib64/python2.6/site-packages/simplejson/__init__.py", line 318, in loads
return cls(encoding=encoding, **kw).decode(s)
TypeError: __init__() got an unexpected keyword argument 'object_pairs_hook'
我在python 2.6.6上,而simplejson版本是2.0.9。有没有办法将json文件加载到OrderedDict中?目的是读取json,添加一些条目,然后打印出来,保留原始json文件的顺序。
修改
升级simplejson之后它仍然无效 - 由pip和脚本报告了不同版本的simplejson。我在脚本中添加了以下内容:
print "simplejson version: " + json.__version__
print "simplejson path: " + json.__file__
打印:
simplejson version: 2.0.9
simplejson path: /usr/lib64/python2.6/site-packages/simplejson/__init__.pyc
然而,pip报道:
$ pip show simplejson
DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
Name: simplejson
Version: 3.10.0
Summary: Simple, fast, extensible JSON encoder/decoder for Python
Home-page: http://github.com/simplejson/simplejson
Author: Bob Ippolito
Author-email: bob@redivi.com
License: MIT License
Location: /usr/lib64/python2.6/site-packages
Requires:
两者都报告了simplejson模块的相同位置,似乎都安装了:
$ ls -ld /usr/lib64/python2.6/site-packages/simplejson*
drwxr-xr-x 3 root root 4096 May 9 15:29 /usr/lib64/python2.6/site-packages/simplejson
drwxr-xr-x 2 root root 4096 May 9 15:29 /usr/lib64/python2.6/site-packages/simplejson-2.0.9-py2.6.egg-info
drwxr-xr-x 2 root root 4096 May 9 09:10 /usr/lib64/python2.6/site-packages/simplejson-3.10.0-py2.6.egg-info
如何确保python使用3.10.0版本而不是2.0.9?