python - Python中的JSON输出排序

我在 python 中遇到了 JSON 的问题。

事实上,如果我尝试执行这段代码,python 会给我一个排序好的 JSON 字符串!

例如:

values = {
  'profile': 'testprofile',
  'format': 'RSA_RC4_Sealed',
  'enc_key': base64.b64encode(chiave_da_inviare),
  'request': base64.b64encode(data)
}

values_json = json.dumps(values, sort_keys = False, separators = (',', ':'))

这是输出:

{
  "profile": "testprofile",
  "enc_key": "GBWo[...]NV6w==",
  "request": "TFl[...]uYw==",
  "format": "RSA_RC4_Sealed"
}

如您所见,我尝试使用“sort_keys=False”但没有任何改变。

如何停止 Python 对 JSON 字符串进行排序?

最佳答案

试试 OrderedDict来自标准库 collections :

>>> import json
>>> from collections import OrderedDict
>>> values = OrderedDict([('profile','testprofile'), 
                          ('format', 'RSA_RC4_Sealed'), 
                          ('enc_key', '...'), 
                          ('request', '...')])
>>> json.dumps(values, sort_keys=False)
'{"profile": "testprofile", "format": "RSA_RC4_Sealed", "enc_key": "...", "request": "..."}'

不幸的是,此功能是 2.7 版中的新功能,适用于 collections

https://stackoverflow.com/questions/2774361/

相关文章:

c# - 在 C# 中通过 POST 发送 JSON 并接收返回的 JSON?

c# - 使用 JsonConvert.DeserializeObject 将 Json 反序列化为

javascript - 如何将 JavaScript 对象编码为 JSON?

ruby-on-rails - 使用 Rspec,如何在 Rails 3.0.11 中测试我的 Co

c# - 将日期时间从 javascript 传递给 c# (Controller)

c# - Json.Net 中的 PreserveReferencesHandling 和 Refe

json - 如何对 Windows Azure 动态内容启用 gzip HTTP 压缩

android - JSONException : Value of type java. lang

asp.net - 我可以将 JSON 字符串转换为 JsonResult 吗?

javascript - 使用 JSON 制作 XmlHttpRequest POST