问题描述
我有一个 .json 文件(将其命名为 meta.json),如下所示:
I got a .json file (named it meta.json) like this:
{ "main": { "title": "今日は雨が降って", "description": "今日は雨が降って" } }
我想将其转换为 .yaml 文件(将其命名为 meta.yaml),例如:
I would like to convert it to a .yaml file (named it meta.yaml) like :
title: "今日は雨が降って" description: "今日は雨が降って"
我所做的是:
import simplejson as json import pyyaml f = open('meta.json', 'r') jsonData = json.load(f) f.close() ff = open('meta.yaml', 'w+') yamlData = {'title':'', 'description':''} yamlData['title'] = jsonData['main']['title'] yamlData['description'] = jsonData['main']['description'] yaml.dump(yamlData, ff) # So you can see that what I need is the value of meta.json
但遗憾的是,我得到的是以下内容:
But sadly, what I got is following:
{description: "u4ECAu65E5u306Fu96E8u304Cu964Du3063u3066", title: "u4ECAu65E5 u306Fu96E8u304Cu964Du3063"}
为什么?
推荐答案
pyyaml.dump() 有 "allow_unicode" 选项,默认为 None,输出中的所有非 ASCII 字符都被转义.如果 allow_unicode=True 则写入原始 unicode 字符串.
pyyaml.dump() has "allow_unicode" option, it's default is None, all non-ASCII characters in the output are escaped. If allow_unicode=True write raw unicode strings.
yaml.dump(data, ff, allow_unicode=True)
奖金
json.dump(data, outfile, ensure_ascii=False)