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

时间:2016-12-28 18:11:46

标签: python json

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

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

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

,则会出现同样的错误

1 个答案:

答案 0 :(得分:1)

您可以提供 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 蛋将位于:

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

&lt; version&gt; simplejson 版本,&lt; python&gt; 是Python版本,&lt; os&gt; 是操作系统,&lt; arch&gt; 是处理器架构。在我的机器上,这导致:

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