Python json.loads更改对象的顺序 [英] Python json.loads changes the order of the object

查看:371
本文介绍了Python json.loads更改对象的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含JSON对象的文件.已通过以下方式加载:

I've got a file that contains a JSON object. It's been loaded the following way:

with open('data.json', 'r') as input_file:
  input_data = input_file.read()

这时,input_data仅包含一个字符串,现在我将其解析为JSON:

At this point input_data contains just a string, and now I proceed to parse it into JSON:

data_content = json.loads(input_data.decode('utf-8'))

data_content具有我需要的字符串的JSON表示形式,但是由于某种原因,在json.loads之后我不清楚,它正在更改键的原始顺序,例如,如果我的文件包含类似:

data_content has the JSON representation of the string which is what I need, but for some reason not clear to me after json.loads it is altering the order original order of the keys, so for instance, if my file contained something like:

{ "z_id": 312312,
  "fname": "test",
  "program": "none",
  "org": null
}

在json.loads之后,顺序被更改为类似这样的内容:

After json.loads the order is altered to let's say something like:

{ "fname": "test",
  "program": None,
  "z_id": 312312,
  "org": "none"
}

为什么会这样?有没有办法保留订单?我正在使用Python 2.7.

Why is this happening? Is there a way to preserve the order? I'm using Python 2.7.

推荐答案

python中的字典(对象)没有确定的顺序.因此,当解析为dict时,该顺序将丢失.

Dictionaries (objects) in python have no guaranteed order. So when parsed into a dict, the order is lost.

如果顺序由于某些原因很重要,则可以让json.loads使用OrderedDict代替,就像dict,但是键的顺序已保存.

If the order is important for some reason, you can have json.loads use an OrderedDict instead, which is like a dict, but the order of keys is saved.

from collections import OrderedDict

data_content = json.loads(input_data.decode('utf-8'), object_pairs_hook=OrderedDict)

这篇关于Python json.loads更改对象的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆