Python:在json文件中将编码字符串解码为utf8

2024-04-29 20:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有超过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字符串


Tags: 文件字符串nameidjson编码typestandard
2条回答

如果您使用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")
data = "\u041c\u043e\u0441\u043a\u0432\u0430"
data = data.encode().decode('unicode-escape')

这可能是一个解决方案

相关问题 更多 >