问题
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...
回答1:
Use a dash to start a new list element:
models:
- model: "a"
type: "x"
#bunch of properties...
- model: "b"
type: "y"
#bunch of properties...
回答2:
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).
来源:https://stackoverflow.com/questions/30221348/building-an-array-of-dictionary-items-in-yaml