[python小工具]-JSON字符串排序

[python小工具] - JSON字符串排序

开发过程中一些JSON字符串没有按照a-z排序阅读性差,随手写了python进行排序和格式化的小工具

# -*- coding: utf-8 -*-
# JSON 字段排序
import json

# 文件路径
file_path = "/Users/your-home/data/order.json"

# 读取文件
def read_file():
    json_content = ""
    with open(file_path) as lines:
        array = lines.readlines()
        for i in array:
            json_content += i
    return json_content

# JSON 排序格式化
def json_sort(json_content):
    dict_json = json.loads(json_content)
    json_content = json.dumps(dict_json, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)
    return json_content

# 写回文件
def write_file(content):
    f = open(file_path, "w", encoding="utf-8")
    f.write(content)
    f.flush()
    f.close()


if __name__ == '__main__':
    json_str = read_file()
    json_str = json_sort(json_str)
    write_file(json_str)
    print(json_str)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值