Python 修改json文件保留转义符的笨办法

有一批json文件需要进行批量处理,流程基本上是 json.loads(f.read())f.write(json.dumps(json_)),但是这些文件之前还有的转义符会被自动去掉,由于是通过 git 进行同步的,修改记录会特别多,只能想个办法手动处理一下。

with open(file, "r+", encoding="utf-8") as f:
    origin_content = f.read()
    json_ = json.loads(origin_content)

    # 对json内容进行修改
    update_json = {"key1": "value1", "key2": "value2"}
    json_.update(update_json)

    # 这样操作可以实现一次操作,先读取,再写入
    f.seek(0)
    f.write(json.dumps(json_, indent=4, ensure_ascii=False))
    f.truncate()

# 这里是保持不因为 \/ 被改成 / 导致大量修改,可以忽略
with open(file, "r+", encoding="utf-8") as f:
    # 文件当前内容
    current_content = f.read()

    # 当前内容和修改前的内容,都按行分割
    origin_content_lines = origin_content.splitlines()
    current_content_lines = current_content.splitlines()

    # 单独对比每一行,如果只是少了 \ 使用修改前的那一行
    for line, current_line in enumerate(current_content_lines):
        current_line = list(current_line)

        try:
            origin_line = list(origin_content_lines[line])
            line_diff = list(
                set([i for i in origin_line if i not in current_line])
            )
            if line_diff == ["\\"] or len(line_diff) == 0:
                current_content_lines[line] = origin_content_lines[line]
        except:
            pass

    for i_, line_ in enumerate(current_content_lines[:-2]):
        if not line_.endswith(",") and line_ not in ["{", "}"]:
        current_content_lines[i_] += ","

    # 重新写入内容
    f.seek(0)
    f.write("\n".join(current_content_lines))
    f.truncate()
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇