I got a .json
file (named it meta.json
) like this:
JavaScript
x
7
1
{
2
"main": {
3
"title": "今日は雨が降って",
4
"description": "今日は雨が降って"
5
}
6
}
7
I would like to convert it to a .yaml
file (named it meta.yaml
) like :
JavaScript
1
3
1
title: "今日は雨が降って"
2
description: "今日は雨が降って"
3
What I have done was :
JavaScript
1
14
14
1
import simplejson as json
2
import pyyaml
3
4
f = open('meta.json', 'r')
5
jsonData = json.load(f)
6
f.close()
7
8
ff = open('meta.yaml', 'w+')
9
yamlData = {'title':'', 'description':''}
10
yamlData['title'] = jsonData['main']['title']
11
yamlData['description'] = jsonData['main']['description']
12
yaml.dump(yamlData, ff)
13
# So you can see that what I need is the value of meta.json
14
But sadly, what I got is following:
JavaScript
1
3
1
{description: "u4ECAu65E5u306Fu96E8u304Cu964Du3063u3066", title: "u4ECAu65E5
2
u306Fu96E8u304Cu964Du3063"}
3
Why?
Advertisement
Answer
pyyaml.dump()
has an allow_unicode
option that defaults to None
(all non-ASCII characters in the output are escaped). If allow_unicode=True
, then it writes raw Unicode strings.
JavaScript
1
2
1
yaml.dump(data, ff, allow_unicode=True)
2
Bonus
You can dump JSON without encoding as follows:
JavaScript
1
2
1
json.dump(data, outfile, ensure_ascii=False)
2