我正在尝试使用Python进行简单的YAML到JSON转换器,但它看起来似乎不正确。我是一个本地的Perl / Ruby程序员,所以我有三个脚本和一个输入文件:
testinput.yaml
---
default:
default:
line_one: '[I]<description>[/I]'
line_three: '<creator>'
line_two: '<title> [<type>]'
link_to: '<citation>'
和一个Python / Perl / Ruby脚本,每个在我的脑海中完全相同:
y2j.rb
require 'rubygems'
require 'json'
require 'yaml'
yml = YAML.load_file('testinput.yaml')
json = JSON.dump(yml)
puts json
y2j.pl
use JSON;
use YAML;
my $filename = "testinput.yaml";
my $yaml = YAML::LoadFile($filename);
print encode_json($yaml);
y2j.py
import yaml
import json
stream = open("testinput.yaml", 'r')
data = yaml.load_all(stream)
json = json.dumps(data)
print(json)
enter code here
然后输出:
ruby y2j.rb
{"default":{"default":{"link_to":"<citation>","line_two":"<title> [<type>]","line_three":"<creator>","line_one":"[I]<description>[/I]"}}}
perl y2j.pl
{"default":{"default":{"line_three":"<creator>","line_two":"<title> [<type>]","link_to":"<citation>","line_one":"[I]<description>[/I]"}}}
(到目前为止,很好)
python y2j.py
Traceback (most recent call last):
File "y2j.py", line 7, in <module>
json = json.dumps(data)
File "/usr/lib64/python2.6/json/__init__.py", line 230, in dumps
return _default_encoder.encode(obj)
File "/usr/lib64/python2.6/json/encoder.py", line 367, in encode
chunks = list(self.iterencode(o))
File "/usr/lib64/python2.6/json/encoder.py", line 317, in _iterencode
for chunk in self._iterencode_default(o, markers):
File "/usr/lib64/python2.6/json/encoder.py", line 323, in _ iterencode_default
newobj = self.default(o)
File "/usr/lib64/python2.6/json/encoder.py", line 344, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <generator object load_all at 0x15a81e0> is not JSON serializable
我在这里缺少一些完全明显的东西吗?
答案 0 :(得分:2)
yaml.load_all
为generator。请参阅the documentation中的以下示例:
>>> for data in yaml.load_all(documents):
... print data
{'description': 'A set of handgear with sparks that crackle across its knuckleguards.\n',
'name': "The Set of Gauntlets 'Pauraegen'"}
{'description': 'A set of gauntlets that gives off a foul, acrid odour yet remains untarnished.\n',
'name': "The Set of Gauntlets 'Paurnen'"}
{'description': 'A set of handgear, freezing with unnatural cold.\n',
'name': "The Set of Gauntlets 'Paurnimmen'"}
请注意,此代码迭代生成器以访问其内容。
相反,您应该load
数据(或者,为了降低安全风险,safe_load
)。我认为你的Python版本应该如下:
import json
import yaml
with open("testinput.yaml") as stream:
yaml_data = yaml.safe_load(stream)
json_data = json.dumps(yaml_data)
print(json_data)
请注意以下事项:
import
按the style guide; with
上下文管理器来处理文件;和json_data
以避免遮蔽json
库。如果将在文件中包含多个文档,您可以尝试例如yaml_data = list(yaml.load_all(stream))
。