Building an array of dictionary items in YAML?

前端 未结 2 1451
醉话见心
醉话见心 2021-02-06 20:36

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

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


        
2条回答
  •  醉酒成梦
    2021-02-06 20:51

    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).

提交回复
热议问题