python - json.dump() 在 Windows 和 Linux 上的不同行为

标签 python json linux windows python-requests

我编写了一个 python 脚本,使用请求库以 json 格式从网站检索数据,然后将其转储到一个 json 文件中。我已经使用这些数据编写了很多代码,并且仅在 Windows 中对其进行了测试。最近换了个linux系统,执行同样的python脚本时,json文件中key的顺序完全不一样。

这是我正在使用的代码:

API_request = requests.get('https://www.abcd.com/datarequest')
                    alertJson_Data = API_request.json()         # To convert returned data to json
json.dump(alertJson_Data, jsonDataFile)     # for adding the json data for the alert to the file
jsonDataFile.write('\n')
jsonDataFile.close()

我的许多其他脚本都依赖于此 json 文件中键的顺序,那么有什么方法可以保持在 Windows 中使用的顺序与在 Linux 中使用的顺序相同吗? 例如,在 Windows 中,顺序是 "id":, "src":, "dest":, 而在 Linux 中则完全不同。如果我直接在浏览器上访问 Web 链接,它的顺序与 Windows 中保存的顺序相同。如何保留此顺序?

最佳答案

你能用collections.OrderedDict吗?加载 json?

例如

from collections import OrderedDict
alertJson_Data = API_request.json(object_pairs_hook=OrderedDict)

应该有效,因为 json()在请求上实现的方法采用与 json.loads

相同的可选参数

json(**kwargs)

Returns the json-encoded content of a response, if any. Parameters **kwargs – Optional arguments that json.loads takes. Raises ValueError – If the response body does not contain valid json.

以及 json.loads 的文档指定:

object_hook, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given dict. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting).

object_pairs_hook, if specified will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict() will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.

关于python - json.dump() 在 Windows 和 Linux 上的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44846319/

相关文章:

python - 函数制作

java - 改造 - java.lang.IllegalStateException : Expected BEGIN_ARRAY but was BEGIN_OBJECT

python - 如何在 Linux 中配置 sys.path 变量?

linux - 在 Linux 下添加 Sphinx 搜索守护进程作为服务。

linux - 红帽百胜心跳

python - 如何用汉字打印 tesseract 结果

python - 如何修复Python中的 "AttributeError: type object has no attribute"?

python Pandas : Calculate moving average within group

c# - 将数据作为键名包含在 JSON 中是否正确?

c# - 使用 Json.NET 中的 JsonConvert 类检测反序列化对象是否缺少字段