python json文件数据有序加载与导出

主要关注两点:
1. json文件数据加载有序
json_data = json.load(cur_file,object_pairs_hook=collections.OrderedDict)
2. 导出数据缩进格式化:
cur_file.write(json.dumps(json_data,indent=4))
#!/usr/bin/env python3
# encoding: utf-8
# coding style: pep8
# ====================================================
#   Copyright (C)2020 All rights reserved.
#
#   Author        : xxx
#   Email         : [email protected]
#   File Name     : main.py
#   Last Modified : 2020-03-09 17:48
#   Description   :
#
# ====================================================
import sys
import os
import json
import collections

def lm_tag_checkout(filename,tag_namespace):
    cur_file = open(filename,"r+")
    json_data = json.load(cur_file,object_pairs_hook=collections.OrderedDict)	# object_pairs_hook=collections.OrderedDict,确保有序加载数据
    if COMMENT_SWITCH:
        print("old tag:",json_data["tag"])
    json_data["tag"] = "xxx"+str(tag_namespace)
    if COMMENT_SWITCH:
        print("new tag:",json_data["tag"])
    cur_file.seek(0)    #
    cur_file.truncate() #清空文件,配合seek使用,否则清空的位置不对
    cur_file.write(json.dumps(json_data,indent=4))	# indent=4,确保json文件内容缩进格式化
    cur_file.close()

猜你喜欢

转载自blog.csdn.net/zxcasd11/article/details/105203252