【问题标题】:Python: decode encoded string to utf-8 inside json filePython:将编码字符串解码为 json 文件中的 utf-8
【发布时间】:2020-03-20 07:45:14
【问题描述】:

我有超过 1GB 的 json 文件,里面有编码的字符串。例如:

{
    "id": "3",
    "billing_type": {
        "id": "standard",
        "name": "\u0421\u0442\u0430\u043d\u0434\u0430\u0440\u0442"
    },
    "area": {
        "id": "1",
        "name": "\u041c\u043e\u0441\u043a\u0432\u0430"
    }
}

在我的情况下,我如何在我的 json 文件中像 \u041c\u043e 这样的字符串解码?

【问题讨论】:

标签: python json python-3.x encoding utf-8


【解决方案1】:

如果您使用 python3,只需 import json 会有所帮助。

import json


result = json.loads(json_data)
print(result)

或者python2,你应该对每个值使用encode方法(先检查类型之后)

result = json.loads(json_data)

for k, v in result.items():
    if isinstance(v, dict):
        for dk, dv in v.items():
            print dk.encode("utf-8"), dv.encode("utf-8")
    else:
        print k.encode("utf-8"), v.encode("utf-8")

【讨论】:

    【解决方案2】:
    data = "\u041c\u043e\u0441\u043a\u0432\u0430"
    data = data.encode().decode('unicode-escape')
    

    这可能是一个解决方案。

    【讨论】:

      猜你喜欢
      • 2018-11-05
      • 1970-01-01
      • 2019-09-15
      • 2011-08-09
      • 1970-01-01
      • 2011-08-27
      • 2014-01-18
      • 2012-10-18
      相关资源
      最近更新 更多