如何使用Python 3 json.dumps固定JSON密钥顺序? [英] How do I keep the JSON key order fixed with Python 3 json.dumps?

查看:440
本文介绍了如何使用Python 3 json.dumps固定JSON密钥顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在Python 3的json.dumps实现上有一些奇怪的行为,即每次从执行到执行都转储相同的对象时,键顺序都会改变.由于我不在乎对键进行排序,因此谷歌搜索无法正常工作,我只希望它们保持不变!这是一个示例脚本:

I've noticed some strange behavior on Python 3's implementation of json.dumps, namely the key order changes every time I dump the same object from execution to execution. Googling wasn't working since I don't care about sorting the keys, I just want them to remain the same! Here is an example script:

import json

data = {
    'number': 42,
    'name': 'John Doe',
    'email': 'john.doe@example.com',
    'balance': 235.03,
    'isadmin': False,
    'groceries': [
        'apples',
        'bananas',
        'pears',
    ],
    'nested': {
        'complex': True,
        'value': 2153.23412
    }
}

print(json.dumps(data, indent=2))

运行此脚本时,每次都会得到不同的输出,例如:

When I run this script I get different outputs every time, for example:

$ python print_data.py 
{
  "groceries": [
    "apples",
    "bananas",
    "pears"
  ],
  "isadmin": false,
  "nested": {
    "value": 2153.23412,
    "complex": true
  },
  "email": "john.doe@example.com",
  "number": 42,
  "name": "John Doe",
  "balance": 235.03
}

但是随后我再次运行它,我得到了:

But then I run it again and I get:

$ python print_data.py 
{
  "email": "john.doe@example.com",
  "balance": 235.03,
  "name": "John Doe",
  "nested": {
    "value": 2153.23412,
    "complex": true
  },
  "isadmin": false,
  "groceries": [
    "apples",
    "bananas",
    "pears"
  ],
  "number": 42
}

我知道字典是无序集合,并且该顺序基于哈希函数;但是在Python 2中-顺序(无论是什么顺序)都是固定的,并且不会在每次执行的基础上发生变化.这里的困难在于,这使我的测试难以运行,因为我需要比较两个不同模块的JSON输出!

I understand that dictionaries are unordered collections and that the order is based on a hash function; however in Python 2 - the order (whatever it is) is fixed and doesn't change on a per-execution basis. The difficulty here is that it's making my tests difficult to run because I need to compare the JSON output of two different modules!

知道发生了什么吗?如何解决?请注意,我想避免使用OrderedDict或执行任何排序,重要的是两次执行之间字符串表示形式保持不变.同样,这仅用于测试目的,对模块的实现没有任何影响.

Any idea what is going on? How to fix it? Note that I would like to avoid using an OrderedDict or performing any sorting and what matters is that the string representation remains the same between executions. Also this is for testing purposes only and doesn't have any effect on the implementation of my module.

推荐答案

Python字典和JSON对象是无序的.您可以可以要求json.dumps()对输出中的键进行排序;这是为了简化测试.将sort_keys参数用于True:

Python dictionaries and JSON objects are unordered. You can ask json.dumps() to sort the keys in the output; this is meant to ease testing. Use the sort_keys parameter to True:

print(json.dumps(data, indent=2, sort_keys=True))

请参见订单为何在Python词典中设置为任意值?为什么每次看到的顺序都不相同.

See Why is the order in Python dictionaries and sets arbitrary? as to why you see a different order each time.

您可以将 PYTHONHASHSEED环境变量设置为一个整数值,以锁定"字典顺序;仅用于运行测试而不用于生产,因为散列随机化的全部目的是防止攻击者轻易地对程序进行DOS操作.

You can set the PYTHONHASHSEED environment variable to an integer value to 'lock' the dictionary order; use this only to run tests and not in production, as the whole point of hash randomisation is to prevent an attacker from trivially DOS-ing your program.

这篇关于如何使用Python 3 json.dumps固定JSON密钥顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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