2017-05-04 129 views
-2

我试图将json文件加载到一个OrderedDict中,后面跟着mjhm的回答Can I get JSON to load into an OrderedDict in Python?。我开始只是一个JSON字符串为简单起见,代码为:在python 2.6中将JSON加载到OrderedDict - 意外的关键字错误

#!/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' 

我对蟒蛇2.6.6而simplejson版本是2.0.9。有没有一种方法可以用来将Json文件加载到OrderedDict中?目的是读取json,添加一些条目,然后打印出来,保留原始json文件的顺序。

编辑:

升级simplejson它仍然无法正常工作后 ​​- 不同版本simplejson是由PIP和脚本的报道。我增加了以下的脚本:

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: [email protected] 
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?

+0

更新你的'simplejson'。 – user2357112

回答

1
+0

尝试过'pip install -Iv simplejson 2.1.0',但得到:找不到2.1.0的匹配分布。不确定要安装哪个版本,可以在Python 2.6.6中使用。我需要担心兼容性问题吗? – Lidia

+0

@Lidia:只需更新到最新版本。 – user2357112

+0

'sudo pip install simplejson --upgrade'诀窍:成功安装了simplejson-3.10.0 – Lidia

相关问题