美文网首页程序员
python用json模块读取json文件乱序

python用json模块读取json文件乱序

作者: 求余的小屋 | 来源:发表于2023-01-31 23:22 被阅读0次

问题场景

  • python 版本: 3.6
  • 操作系统: windows / linux

当我们用 json.loads 读取了一份 Json 文件中的数据(反序列化,转换为 python 可以处理的数据类型)

修改了某些键的值,再使用 json.dumps 将修改以后的数据,存入新的 json 文件时(序列化)

可能会遇到所有的 key 值乱序的情况,如下所示

  1. 修改前
{
    "key1": "value1",
    "key2": "value2",
}
  1. 修改完成, json.dumps 重新写入文件中,出现乱序
{
    "key2": "modify",
    "key1": "value1"
}

解决方案

为了确保将修改以后的数据,在序列化写入新的 json 文件时,不会出现乱序的情况

我们需要使用 json.loads 提供的 object_paris_hook可选参数

在使用 json.loads 反序列化为 python 中的数据类型时候

结合 collections 模块的 OrderedDict 方法,使得反序列化,得到的有序的字典对象

确保 key 在修改完成以后不会乱序

#!/usr/bin/python3

import json
import collections

# 用于修改 json 数据的内容的函数
def modify_js_file(data_dict: str, target_key, target_value) -> dict:
    """修改js文件中任意 key 的 值"""
    pass

# 读取 json_file.json 文件中的内容
with open("json_file.json") as js_file:
    # 给 object_hook 参数,传入 collections.OrderdDict 方法
    data_dict = json.loads(js_file.read(), object_pairs_hook=collections.OrderedDict)
    # 执行修改数据内容的函数
    result = modify_js_value(data_dict, "key1", "new_value")
    # 修改后的内容,写入 new_json.json 文件中
    with open("new_json.json", 'w') as new_js_file:
        # 缩进为 4 个空格, 允许中文字符
        new_js.write(json.dumps(result), indent=4, ensure_ascii=False)
        print("修改完成")

json.loads 中有趣的参数

在解决这个问题的时候,还发现一个有趣的参数
json.dumpsseprators,会影响转换 json 字符串的格式
下一篇笔记再详细分享~

本文由mdnice多平台发布

相关文章

网友评论

    本文标题:python用json模块读取json文件乱序

    本文链接:https://www.haomeiwen.com/subject/yynbhdtx.html