簡體   English   中英

如何在不刪除unicode的情況下從外殼中使用json.tool來驗證和打印漂亮的語言文件?

[英]How to use json.tool from the shell to validate and pretty-print language files without removing the unicode?

Ubuntu 16.04
重擊4.4
python 3.5

我從Upwork的翻譯那里收到了一堆語言文件,但沒有一個文件有相同的行數。 因此,我決定對它們進行驗證和漂亮打印,因為它們采用.json格式,然后查看每個文件中缺少哪些行,因此我制作了一個簡單的腳本來驗證和漂亮打印:

#!/bin/sh

for file in *.json; do
   python -m json.tool "${file}" > "${file}".tmp;
   rm -f "${file}";
   mv "${file}".tmp "${file}"
done

現在我的俄語Langauge文件看起來像:

"manualdirections": "\u041c\u0430\u0440\u0448\u0440\u0443\u0442",
"moreinformation": "\u0414\u0435\u0442\u0430\u043b\u0438",
"no": "\u041d\u0435\u0442",

我非常想保持文件內容不變。

這在json.tool是不可能的:

https://github.com/python/cpython/blob/3.5/Lib/json/tool.py#L45

調用json.dumps不允許傳遞關鍵字參數ensure_ascii=False ,這將在這里解決您的問題。

您將必須編寫自己的json.tool ,對其進行monkeypatch或使用第三方代碼。

編輯:我建議PR 9765將此功能添加到Python 3.8中的json.tool中。

#!/usr/bin/python3

for filename in os.listdir('/path/to/json_files'):
    if filename.endswith('.json'):
        with open(filename, encoding='utf-8') as f:
            data = f.read()
            print(json.dumps(data, indent=4))

注意open()使用的encoding 這應該導入文件並根據需要顯示它們。 我認為。

您可以改用以下等效的Python腳本,該腳本使用json.JSONEncoder的子類來覆蓋ensure_ascii選項:

import json
import os
import glob

class allow_nonascii(json.JSONEncoder):
    def __init__(self, *args, ensure_ascii=False, **kwargs):
        super().__init__(*args, ensure_ascii=False, **kwargs)

for file in glob.iglob('*.json'):
    with open(file, 'r') as fin, open(file + '.tmp', 'w') as fout:
        fout.write(json.dumps(json.load(fin), cls=allow_nonascii, indent=4))
        os.remove(file)
        os.rename(file + '.tmp', file)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM