94

Basically trying to something in yaml that could be done using this json:

{
models:
 [
  { 
    model: "a"
    type: "x"
    #bunch of properties...
  },
  {
    model: "b"
    type: "y"
    #bunch of properties...
  }
 ]
}

So far this is what I have, it does not work because I am repeating my model key but what can be a proper way to do that by keeping that model key word?

models:
 model:
  type: "x"
  #bunch of properties...
 model:
  type: "y"
  #bunch of properties...
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
sadaf2605
  • 7,332
  • 8
  • 60
  • 103
  • 2
    Have you tried loading your JSON code into a native data structure (in your language of choice), then using a YAML library to serialize that structure? Always easier to let the machine do the work for you. :) – Charles Duffy May 13 '15 at 17:19

2 Answers2

194

Use a dash to start a new list element:

models:
 - model: "a"
   type: "x"
   #bunch of properties...
 - model: "b"
   type: "y"
   #bunch of properties...
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
92

You probably have been looking at YAML for too long because that what you call JSON in your post isn't, it is more a half-and-half of YAML and JSON. Lets skip the fact that JSON doesn't allow comments starting with a #, you should quote the strings that are keys and you should put , between elements in mapping:

{
"models":
 [
  {
    "model": "a",
    "type": "x"
  },
  {
    "model": "b",
    "type": "y"
  }
 ]
}

That is correct JSON as well as it is YAML, because YAML is a superset of JSON. You can e.g. check that online at this YAML parser.

You can convert it to the block-style you seem to prefer as YAML using ruamel.yaml.cmd (based on my enhanced version of PyYAML: pip install ruamel.yaml.cmd). You can use its commandline utility to convert JSON to block YAML (in version 0.9.1 you can also force flow style):

yaml json in.json

which gets you:

models:
- model: a
  type: x
- model: b
  type: y

There are some online resources that allow you to do the above, but as with any of such services, don't use them for anything important (like the list of credit-card numbers and passwords).

Anthon
  • 69,918
  • 32
  • 186
  • 246
  • 20
    This really *is* the better answer. I'm a bit embarrassed to have mine accepted. – Charles Duffy Jan 18 '17 at 16:44
  • 4
    Thanks, but looking at the upvote counts, obviously your answer serves a need and mine doesn't. – Anthon Jan 18 '17 at 17:10
  • 3
    I'm chalking it down to the "what folks want" vs "what folks need" dichotomy. The points you're making here are important ones -- someone who generates YAML using a tool such as JQ and then converts it to block-style if they prefer with the tools you link is going to have a much more robust solution than someone who tries to hand-generate text to fit an example. – Charles Duffy Jan 18 '17 at 17:28