json 中的编码或 python 中的 yaml 文件是否有意义?
Does the encoding make sense in json or yaml files in python?
我尝试将此词典保存在 json 或 yaml 文件中:
d = {'name': 'María Gómez', 'message': '¡Es una caña atómica!'}
with open(file, 'wt', encoding='iso8859-1') as file:
json.dump(d, file)
但是,文件内容不在该编码中,非 ascii 字符在 json 或 yaml 文件中转义。因此,我认为编码文件没有意义。或者是否有一些语言或字符的编码对此类文件有意义?
import json
d = {'name': 'María Gómez', 'message': '¡Es una caña atómica!'}
json.dumps(d)
# '{"name": "Mar\u00eda G\u00f3mez", "message": "\u00a1Es una ca\u00f1a at\u00f3mica!"}'
json.dumps(d, ensure_ascii=False)
# '{"name": "María Gómez", "message": "¡Es una caña atómica!"}'
说明(对json.dumps
和json.dump
有效):JSON encoder and decoder basic usage:
If ensure_ascii
is true (the default), the output is guaranteed to
have all incoming non-ASCII characters escaped. If ensure_ascii
is
false, these characters will be output as-is.
我尝试将此词典保存在 json 或 yaml 文件中:
d = {'name': 'María Gómez', 'message': '¡Es una caña atómica!'}
with open(file, 'wt', encoding='iso8859-1') as file:
json.dump(d, file)
但是,文件内容不在该编码中,非 ascii 字符在 json 或 yaml 文件中转义。因此,我认为编码文件没有意义。或者是否有一些语言或字符的编码对此类文件有意义?
import json
d = {'name': 'María Gómez', 'message': '¡Es una caña atómica!'}
json.dumps(d)
# '{"name": "Mar\u00eda G\u00f3mez", "message": "\u00a1Es una ca\u00f1a at\u00f3mica!"}'
json.dumps(d, ensure_ascii=False)
# '{"name": "María Gómez", "message": "¡Es una caña atómica!"}'
说明(对json.dumps
和json.dump
有效):JSON encoder and decoder basic usage:
If
ensure_ascii
is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. Ifensure_ascii
is false, these characters will be output as-is.