在YAML中构建一个字典项数组?

sad*_*605 37 yaml pyyaml

基本上尝试使用这个json可以完成的yaml:

{
models:
 [
  { 
    model: "a"
    type: "x"
    #bunch of properties...
  },
  {
    model: "b"
    type: "y"
    #bunch of properties...
  }
 ]
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我所拥有的,它不起作用,因为我正在重复我的model密钥,但通过保持关键词,这可能是一个正确的方法model吗?

models:
 model:
  type: "x"
  #bunch of properties...
 model:
  type: "y"
  #bunch of properties...
Run Code Online (Sandbox Code Playgroud)

Cha*_*ffy 86

使用短划线开始新的列表元素:

models:
 - model: "a"
   type: "x"
   #bunch of properties...
 - model: "b"
   type: "y"
   #bunch of properties...
Run Code Online (Sandbox Code Playgroud)


Ant*_*hon 36

你可能一直在看YAML太久了,因为你在帖子中称之为JSON的不是,它更像是YAML和JSON的一半.让我们跳过JSON不允许以a开头的注释的事实#,你应该引用作为键的字符串,你应该放在,映射中的元素之间:

{
"models":
 [
  {
    "model": "a",
    "type": "x"
  },
  {
    "model": "b",
    "type": "y"
  }
 ]
}
Run Code Online (Sandbox Code Playgroud)

是正确的JSON以及它是YAML,因为YAML是JSON的超集.您可以在此YAML解析器上在线检查.

您可以使用ruamel.yaml.cmd(基于我的增强版PyYAML :)将它转换为您似乎更喜欢YAML的块样式 pip install ruamel.yaml.cmd.您可以使用其命令行实用程序将JSON转换为块YAML(在版本0.9.1中,您也可以强制流式):

yaml json in.json
Run Code Online (Sandbox Code Playgroud)

哪个让你:

models:
- model: a
  type: x
- model: b
  type: y
Run Code Online (Sandbox Code Playgroud)

有一些在线资源允许您执行上述操作,但与任何此类服务一样,请勿将其用于任何重要事项(例如信用卡号和密码列表).

  • 这真的是*更好的答案.让我接受我有点尴尬. (5认同)
  • 谢谢,但是看看投票数,显然你的回答是有需要的,而我的没有。 (2认同)
  • 我将其归结为“人们想要”与“人们需要”二分法。您在这里提出的要点很重要-使用JQ之类的工具生成YAML,然后将其转换为块样式(如果他们更喜欢使用您链接的工具)的人将比那些尝试手工生成文本以适合示例。 (2认同)