python - How to encode json dump correctly in python
问题描述
I have a python 3 script that should get some data from a .csv-file and write it to a json file. During my processing the encoding is correct, so that german umlauts ü, ä or degree sign ° are like they are (# coding=cp1252 at the head).
But when I write the dict via json.dump() the encoding is gone...
How can I write a dict to a json file with the correct encoding?
# -*- coding: cp1252 -*-
import json
from pandas import read_csv
x={"äö": "ü°"}
print(x, json.dumps(x, indent=4))
>>>> {'äö': 'ü°'} {"\u00e4\u00f6": "\u00fc\u00b0"}
解决方案
This is happening because ä
, ö
, ü
, and °
aren't ASCII characters.
json.dumps
has an optional argument called ensure_ascii
which escapes non-ASCII characters, and it's set to True
by default. You can get your desired behavior by setting this to false.
x={"äö": "ü°"}
print(x, json.dumps(x, ensure_ascii=False, indent=4))
推荐阅读
- pandas - 基于其他列创建具有增量的新列
- swiftui - SwiftUI TextEditor 覆盖忽略 allowHitTesting
- php - 如何在 PHP 中检查某件事是否超过 7 天或 1 个月前?
- angular - 尝试访问我的服务中的功能时出错
- javascript - 为什么 useQuery 调用会导致我的组件重新渲染?
- ssl - OpenSSL SSL_connect:SSL_ERROR_SYSCALL 连接到 www.google.com:443
- sed - 尝试在 WIndows 上编译 gmp-6.2.1 时使用 'char 9: unterminated `s' command' 失败
- ios - AWS amplify add auth:如何在执行 amplify cli 后添加重定向登录 URI
- angular - 在 NativeScript 视图中动态渲染 FontAwesome 图标
- angular - 我被这个错误困住了。当我按照所有步骤在heroku上部署角度应用程序时